LeetCode C++ 387. First Unique Character in a String【String/Hash Table】簡單

memcpy0發表於2020-12-23

Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode"
return 2.

Note: You may assume the string contains only lowercase English letters.

題意:找出字串中第一個不重複的字元。


解法 雜湊

class Solution {
public:
    int firstUniqChar(string s) {
        int cnt[26] = {0}, n = s.size();
        for (const char &c : s) ++cnt[c - 'a'];
        for (int i = 0; i < n; ++i) if (cnt[s[i] - 'a'] == 1) return i;
        return -1;
    }
};

提交後的執行結果:

執行用時:28 ms, 在所有 C++ 提交中擊敗了91.78% 的使用者
記憶體消耗:10.8 MB, 在所有 C++ 提交中擊敗了37.17% 的使用者

相關文章