emmm很容易想到,我们可以直接用哈希表来存储一对<字符,出现次数>的映射,然后对字符串s遍历的时候找到第一个只出现一次的字符,如果没有就返回空格:
class Solution {
public:
char firstUniqChar(string s) {
unordered_map<int,int> count;
for(char &ch:s)
{
++count[ch];
}
for(auto it=s.begin();it!=s.end();++it)
{
if(count[*it]==1)
{
return *it;
}
}
return ' ';
}
};
空间效率:O(n)(扫描两次字符串)
空间效率:O(1)(给定了固定大小的字符集)