系列文章目录
前言
一、剑指 Offer 50. 第一个只出现一次的字符
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
s = "abaccdeff"
返回 "b"
s = ""
返回 " "
限制:
0 <= s 的长度 <= 50000
相关标签
哈希表
二、使用步骤
1.引入库
代码如下:
哈希表
class Solution {
public:
char firstUniqChar(string s) {
unordered_map<char, bool> map;
for( char c:s)
{
map[c]=map.find(c) ==map.end();
}
for(char c:s)
{
if(map[c]) return c;
}
return ' ';
}
};
有序哈希表
class Solution {
public:
char firstUniqChar(string s) {
vector<char> keys;
unordered_map<char, bool> dic;
for(char c : s) {
if(dic.find(c) == dic.end())
keys.push_back(c);
dic[c] = dic.find(c) == dic.end();
}
for(char c : keys) {
if(dic[c]) return c;
}
return ' ';
}
};
作者:Krahets
链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5vu0zv/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
总结
以上就是今天要讲的内容