我试图在 C++ 中使用 unordered_map 查找字符串的第一个唯一字符。 LeetCodeProblem我的代码:
int firstUniqChar(string s) {
unordered_map<char,int> m;
for(int i=0;i<s.length();i++){
m[s[i]]++;
}
unordered_map<char,int>::iterator mit;
for(mit=m.begin();mit!=m.end();mit++){
if(mit->second ==1)
for(int i=0;i<s.length();i++){
if(mit->first == s[i])
return i;
}
}
return -1;
}
输出不正确。 如果我尝试在 eclipse 中调试它,它会说无法解析 unordered_map。我在我的代码中找不到错误。请帮助我理解错误。
最佳答案
unordered_map
不能确保元素按照您插入的顺序存储。因此,当您对其进行迭代时,无法保证 second
为 1 的第一个元素一定是第一个唯一字符。
您应该遍历字符串:
int firstUniqChar(string s) {
unordered_map<char,int> m;
for(int i=0;i<s.length();i++){
m[s[i]]++;
}
for (int i = 0; i < s.length(); i++){
if (m[s[i]] == 1) {
return i;
}
}
return -1;
}
关于c++ - 使用Unordered_map C++的字符串中的第一个唯一字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39609492/