剑指 Offer 50. 第一个只出现一次的字符
· 约 1 分钟阅读 · – 次阅读
leetcode
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例 1:
输入:s = “abaccdeff” 输出:‘b’ 示例 2:
输入:s = "" 输出:’ ‘
哈希表一次遍历
class Solution {
public:
char firstUniqChar(string s) {
unordered_map<char, int> freq;
for (auto ch : s) {
freq[ch]++;
}
for (int i = 0; i < s.size(); i++) {
if (freq[s[i]] == 1) {
return s[i];
}
}
return ' ';
}
};
使用队列+哈希表
class Solution {
public:
char firstUniqChar(string s) {
unordered_map<char, int> position;
queue<pair<char, int>> q;
for (int i = 0; i < s.size(); i++) {
if (!position.count(s[i])) {
position[s[i]] = i;
q.emplace(s[i], i);
}else{
// 如果一个字符非第一次出现
position[s[i]] = -1;
// 将队列头部的非第一次出现的字符弹出
while (!q.empty() && position[q.front().first] == -1) {
q.pop();
}
}
}
// 如果队列为空,说明没有只出现一次的字符;否则队首即为结果
return q.empty() ? ' ' : q.front().first;
}
};