给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

C++

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char, int> m;
        for (char c : s) m[c]++;
        for (int i = 0; i < s.size(); i++) {
            if (m[s[i]] == 1) return i;
        }
        return -1;
    }
};

C

int firstUniqChar(char* s) {
    int i = 0, j = 0;
    int len = strlen(s);
    int freq[26] = { 0 };
    for (i = 0; i < len; i++) {
        freq[s[i] - 'a']++;
    }
    for (i = 0; i < len; i++) {
        if (freq[s[i] - 'a'] == 1)
            return i;
    }
    return -1;
}

C比C++麻烦很多啊。。

参考来源https://www.cnblogs.com/grandyang/

相关文章:

  • 2022-12-23
  • 2021-09-01
  • 2022-03-06
  • 2021-09-27
  • 2021-06-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-26
  • 2021-06-30
  • 2021-11-17
  • 2021-08-08
  • 2022-01-28
  • 2021-10-12
  • 2022-01-03
相关资源
相似解决方案