【问题标题】:First unique character in string using Unordered_map c++使用Unordered_map c ++的字符串中的第一个唯一字符
【发布时间】:2016-09-21 06:59:18
【问题描述】:

我正在尝试使用 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。我在我的代码中找不到错误。请帮助我理解错误。

【问题讨论】:

标签: c++ string unordered-map


【解决方案1】:

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;
}

【讨论】:

  • 哦..我不知道这个。谢谢。但是元素的存储顺序是什么?
  • @rowang 未指定。取决于哈希函数、桶的数量(随时间变化)、哈希值如何映射到桶等。
  • 通过this更好地理解。
  • 谢谢大家。明白了。
猜你喜欢
  • 2021-05-27
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 2013-01-21
  • 2022-01-19
  • 1970-01-01
  • 2021-03-21
相关资源
最近更新 更多