[剑指offer]第一个只出现一次的字符
题目描述
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
s = "abaccdeff"
返回 "b"
s = ""
返回 " "
限制:
0 <= s 的长度 <= 50000
解题思路
- 哈希表,遍历字符串 s ,用哈希表统计各字符数量,再遍历字符串 s ,在哈希表中找到首个数量为1的字符,并返回。
实现代码
class Solution {
public:
char firstUniqChar(string s) {
int len=s.length();
map<char,int> mymap;
for(int i=0;i<len;i++){
mymap[s[i]]++;
}
for(int i=0;i<len;i++){
if(mymap[s[i]]==1)
return s[i];
}
return ' ';
}
};