char firstUniqChar(string &str) {
char c='0';
map<char,int>m;
for(int i=0;i<str.size();i++){
if(m.find(str[i])!=m.end()){
auto it=m.find(str[i]);
it->second=-1;
}
else{
m.insert(make_pair(str[i],i));
}
}
int flag=0;
int min_index = INT_MAX;
for(auto it=m.begin();it!=m.end();it++){
if(it->second!=-1){
if(it->second<min_index){
min_index=it->second;
flag=1;
}
}
}
if(flag)
return str[min_index];
else{
return c;
}
Conclusion:
whenever you see string problems like this one. and you have no idea that how we can solve this problem. then hashmap is always an option for you. hashmap is easy and efficient. it reduces our time complexity.
Best of luck.
Comments
Post a Comment