C++
哈希表,记录是否键值(字符)出现
class Solution {
public:
char firstUniqChar(string s) {
unordered_map<char, bool> map;
for(auto i : s){
if(map.find(i)==map.end()) map[i] = false; //第一次出现,false
else map[i] = true; //map里已经存了,true
}
for(char i:s){
if(!map[i]) return i; //值为false的键,出现一次
}
return ' ';
}
};
Python
class Solution:
def firstUniqChar(self, s: str) -> str:
dic = {}
for c in s:
dic[c] = not c in dic
for c in s:
if dic[c]: return c
return ' '