LC 387. First Unique Character in a String

Nilanjan Deb · April 5, 2020

This is my CPP solution.

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


Dicussion Forum