[LeetCode]字符串——字符串中的第一个唯一字符

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -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++麻烦很多啊。。

猜你喜欢

转载自www.cnblogs.com/moonpie-sun/p/9426575.html