在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例 1:
输入:s = “abaccdeff”
输出:’b’
示例 2:
输入:s = “”
输出:’ ‘
哈希表一次遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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 ' '; } };
|
使用队列+哈希表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| 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; } };
|