Idea: For
this question, we can directly use the map container to solve it. If we still pursue space and time efficiency, we will implement a hash algorithm by ourselves, because the string only involves 26 lowercase letters, then we can use an array ch[] to record the number of each element
- First, we first set the element value to -1
- Then traverse the string. When the value of the ch array corresponding to an element is -1, it means that it has not appeared before, so at this time, set the ch[] element value to the subscript corresponding to the string; if it is greater than or equal to 0, then it means that it has appeared before. At this time, just set the value of the ch[] element to -2, (as long as it is distinguished)
- Just traverse the ch[] array, ignore the -2, -1 elements, and just use a variable to record the minimum value of the array.
Code:
class Solution {
public:
char firstUniqChar(string s) {
char ch=' ';
if(s.size()==0) return ch;
map<char,int> mp;
for(auto &i:s){
mp[i]++;
}
for(auto &i:s){
if(mp[i]==1){
return i;
}
}
return ch;
}
};
//代码二
class Solution {
public:
char firstUniqChar(string s) {
char op = ' ';
if(s.size()==0) return op;
int ch[27];
for(int i=0;i<27;++i){
ch[i] = -1;
}
int ans = INT_MAX;
for(int i=0;i<s.size();++i){
int idx = s[i] - 'a';
if(ch[idx]==-1){
ch[idx] = i;
}else if(ch[idx]>=0){
ch[idx] = -2;
}
}
for(int i=0;i<27;++i){
if(ch[i]>=0){
ans = min(ans,ch[i]);
}
}
if(ans==INT_MAX) return ' ';
else return s[ans];
}
};