387. 字符串中的第一个唯一字符 - 力扣(LeetCode) (leetcode-cn.com)
class Solution {
public int firstUniqChar(String s) {
//方法一:
//先用map存储个字符,重复出现为value为false,只出现一次为true
Map<Character,Boolean> map = new HashMap<>();
for(int i=0;i<s.length();i++){
map.put(s.charAt(i),!map.containsKey(s.charAt(i)));
}
//再获取每个value为true的字符在s中的下标,得到最小值
int min = Integer.MAX_VALUE;
for(Map.Entry<Character,Boolean> m:map.entrySet()){
if(m.getValue()) min = Math.min(min,s.indexOf(m.getKey()));
}
if(min==Integer.MAX_VALUE) return -1;
return min;
//方法二:
//直接判断字符第一次出现和最后一次出现的位置
//如果重复出现则字符第一次出现和最后一次出现下标不同
//如果只出现一次则字符第一次出现和最后一次出现下标相同
for(int i=0;i<s.length();i++){
int firstIndex = s.indexOf(s.charAt(i));
int lastIndex = s.lastIndexOf(s.charAt(i));
if(firstIndex==lastIndex)
return i;
}
return -1;
}
}