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


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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM