自己的题解:利用map的性质
class Solution {
public char firstUniqChar(String s) {
char ch = ' ';
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0)+1);
}
for (int i = 0; i < s.length(); i++) {
if(map.get(s.charAt(i)) == 1) return s.charAt(i);
}
return ch;
}
}
k神:有序哈希表+boolean,更加节约时间
Java可用LinkedList实现有序哈希表
class Solution {
public char firstUniqChar(String s) {
Map<Character, Boolean> dic = new LinkedHashMap<>();
char[] sc = s.toCharArray();
for(char c : sc)
dic.put(c, !dic.containsKey(c));
for(Map.Entry<Character, Boolean> d : dic.entrySet()){
if(d.getValue()) return d.getKey();
}
return ' ';
}
}