题目
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
s = “abaccdeff”
返回 “b”
s = “”
返回 " "
限制:
0 <= s 的长度 <= 50000
代码
Python
# 思路:
# 采用哈希表存储各字符出现次数
# 复杂度:
# O(N)
class Solution:
def firstUniqChar(self, s: str) -> str:
dic={}
for c in s:
dic[c]= not c in dic # 出现一次为true,否则为false
for c in s:
if dic[c]: return c # 寻找第一个只出现一次的字符,即第一个true
return ' '
C++
class Solution {
public:
char firstUniqChar(const string s) {
if (s.empty()) return ' ';
map<char,int> dic;
int a=0,b=0;
while (a<s.size()) {
if (dic.find(s[a])==dic.end()) dic[s[a]]=1;
else dic[s[a]]+=1;
a++;
}
while (b<s.size()) {
if (dic[s[b]]==1) return s[b];
b++;
}
return ' ';
}
};