class Solution {
public int firstUniqChar(String s) {
if(s.length()==1) return 0;
HashMap<Character, Integer> count = new HashMap<Character, Integer>();
int n = s.length();
// build hash map : character and how often it appears
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
count.put(c, count.getOrDefault(c, 0) + 1);
}
// find the index
for (int i = 0; i < n; i++) {
if (count.get(s.charAt(i)) == 1)
return i;
}
return -1;
}
}
字符串中的第一个唯一字符
最新推荐文章于 2020-10-02 22:05:59 发布