leetcode 387 First Unique Character in a String

python:

class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        l = dict()
        for i in list(s):
            if i in l:
                l[i] += 1
            else:
                l[i] = 1
        for index, j in enumerate(list(s)):
            if l[j] == 1:
                return index
        return -1

c++:

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

猜你喜欢

转载自blog.csdn.net/MRxjh/article/details/81031363