387. First Unique Character in a String
考点 | 难度 |
---|---|
Hash Table | Easy |
题目
Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
.
思路
和之前的题解法差不多。先对s
里的每个字母计数,再从头到尾找出来出现次数是1的字母。
答案
public int firstUniqChar(String s) {
HashMap<Character, Integer> counts = new HashMap<Character, Integer>();
int len = s.length();
for (int i = 0; i < len; i++){
char c = s.charAt(i);
counts.put(c, counts.getOrDefault(c, 0) + 1);
}
for (int i = 0; i < len; i++){
if (counts.get(s.charAt(i)) == 1) return i;
}
return -1;
}