C++ 56ms 5 lines


  • 4
    A
    class Solution {
    public:
        int firstUniqChar(string s) {
            int alphabet[26] = {0};
            for (int i = 0; i < s.size(); ++i){++alphabet[s[i] -'a'];}
            int i = 0;
            while (i < s.size() && alphabet[s[i]-'a'] > 1) ++i;
            return i == s.size() ? -1 : i;
        }
    };
    

  • 2
    H
    int firstUniqChar(string s) {
        vector<int> count(26);
        for(int i=0;i<s.size();i++)
            count[s[i]-'a']++;
        for(int i=0;i<s.size();i++)
            if(count[s[i]-'a']==1)
                return i;
        return -1;
    }

  • 0
    D

    @AlgoGuruZ I have the same idea with you but by 60ms.
    But may I ask why this O(N) algorithm cost 56ms? I thought it should be much faster than 56ms, such as 0ms or 4ms....


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.