解法1:用数组hash
class Solution {
public:
char firstUniqChar(string s) {
if (s == "")
return ' ';
int map[26] = {0}; //用栈内存,及时初始化
int len = s.size();
for (int i = 0; i < len; i++) {
map[s[i] - 'a']++;
}
for (int i = 0; i < len; i++)
if (map[s[i] - 'a'] == 1)
return s[i];
return ' ';
}
};
解法2:用unordered_map
class Solution {
public:
char firstUniqChar(string s) {
if (s == "")
return ' ';
unordered_map<char, int> map;
for (const auto& ch : s) {
map[ch]++;
}
for (const auto& ch : s)
if (map[ch] == 1)
return ch;
return ' ';
}
};