哈希表:
对字符串进行两次遍历
查找问题,用哈希表
c++:
class Solution {
public:
char firstUniqChar(string s) {
// 查找问题 可以用哈希表
unordered_map <char, int> mp; // 哈希表
for(auto c:s){
mp[c]++;
}
for(auto c:s){ // 从s中取出key
if( mp[c] == 1)
return c;
}
return ' ';
}
};
python:
class Solution:
def firstUniqChar(self, s: str) -> str:
dic = defaultdict(int) # from collections import defaultdict
for i in s:
dic[i] += 1
for i in s:
if dic[i] == 1:
return i
return ' '