for Robot Artificial Inteligence

14. First Unique Character in a String

|

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

    }
};
  • Brute force solution, traverse string s 2 times. First time, store counts of every character into the hash table, second time, find the first character that appears only once.

Comments