C++ 46ms using vector and set O(n)


  • 0
    H

    I prefer set over unordered_set or unordered_map since it doesn't need hashing
    -> faster

    int firstUniqChar(string s) {
            vector<int> c(26,0);
            set<int> uniq;
            
            //count all characters
            for(int i = 0; i < s.size() ; i++)
                c[s[i] - 'a']++;
                
            //insert characters with count of 1 into set
            for(int i = 0; i < c.size(); i++)
                if(c[i] == 1) uniq.insert(i + 'a');
                
            //return index of the first element erased from the set
            for(int i = 0; i < s.size(); i++)
                if(uniq.erase(s[i])) return i;
                
            return -1;
        }
    

Log in to reply
 

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