解法一:
public class Solution {
//要寻找在字符串中只出现一次的第一个字符的位置,就用Map来统计
//然后遍历字符串,找出第一个只出现一次的字符
public int firstUniqChar(String s) {
HashMap<Character, Integer> map = new HashMap<>();
//统计字符串的map
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(map.containsKey(c)){
map.put(c, map.get(c) + 1);
}
else{
map.put(c, 1);
}
}
//遍历map找出第一个只出现一次的字符
for(int i = 0; i < s.length(); i++){
if(map.get(s.charAt(i)) == 1){
return i;
}
}
return -1;
}
}