①建立一个unordered_map:
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int> pos;
for(int i=0;i<s.size();i++)
pos[s[i]]++;
for(int i=0;i<s.size();i++){
if(pos[s[i]]==1) return i;
}
return -1;}
};
②unordered_map结合queue使用,抄评论区的(感觉没必要,但是学习一下Queue的操作)
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int> position;
queue<pair<char, int>> q;
int n = s.size();
for (int i = 0; i < n; ++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() ? -1 : q.front().second;
}
};