c++ - 使用Unordered_map C++的字符串中的第一个唯一字符

标签 c++ string unordered-map

我试图在 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/

相关文章:

c++ - 我的 x86 目标文件中这些看似无用的 callq 指令有什么用?

c++ - 如何检查字符串中的关键字c++

java - 在 POI 中写入 Excel 工作表之前格式化字符串

java - 我如何在 Java 中比较字符串?

javascript - AngularJS 模型和 Controller 之间的类型错误

c++ - 将 std::set 合并到一个成员变量上

c++ - 使用未覆盖函数的中间派生类在多级继承中覆盖

c++ - unordered_map 使用什么位散列函数?

c++ - 初始化静态 boost::unordered_map

c++ - 散列pair <pair <int,int>,pair <int,int >>的unordered_map