给定一个字符串,返回它的第一个不重复的字符,并返回索引,否则返回-1
class Solution {
public int firstUniqChar(String s) {
HashMap<Character,Integer> m = new HashMap<Character,Integer>();
int n = s.length();
int i;
for(i = 0;i < n;i++){
char c = s.charAt(i);
m.put(c,m.getOrDefault(c,0) + 1);
}
for(i = 0;i < n;i++){
if(m.get(s.charAt(i)) == 1)
return i;
}
return -1;
}
}
本文介绍了一种算法,用于在给定字符串中找到并返回第一个不重复字符及其索引位置。通过使用HashMap数据结构,该算法首先统计每个字符的出现次数,然后再次遍历字符串,返回第一个出现次数为1的字符的索引。

6678

被折叠的 条评论
为什么被折叠?



