原题链接
思路: 先遍历一遍字符串,存储每一个字符的出现次数,再重新遍历一次字符串,比较每个字符的出现次数是否为1,是1,则直接返回
方法1:用HashMap存储字符次数
public int firstUniqChar(String s) {
if(s == null || s.length() == 0) return -1;
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0;i < s.length();i++) {
if(map.containsKey(s.charAt(i))) {
Integer count = map.get(s.charAt(i));
map.put(s.charAt(i), count + 1);
}else {
map.put(s.charAt(i), 1);
}
}
for(int i = 0;i < s.length();i++) {
if(map.get(s.charAt(i)) == 1) return i;
}
return -1;
}
方法2:用数组存储字符次数
public int firstUniqChar(String s) {
int counter[] = new int[26];
for(int i = 0; i < s.length(); i++) counter[s.charAt(i) - 'a']++;
for(int i = 0; i < s.length(); i++){
if(counter[s.charAt(i) - 'a'] == 1) return i;
}
return -1;
}