My solution:
Use unordered_map and vector
Note the difference between unordered_map and map.
The elements in the map are stored according to the binary search tree, and the middle-order traversal can be used to traverse the key values from small to large. (A red-black tree
is implemented internally ) unordered_map internally implements a hash table (also known as a hash table), which accesses records by mapping key code values to a location in the Hash table. The time complexity of the search can reach O (1) , Which is widely used in massive data processing). The arrangement order of its elements is disordered. (It is unordered, not in the order of insertion. I remembered wrong at first, thinking that this question was done in the order of insertion, the first example can't get through ... I have been searching for a long time)
PS: I do n’t know about the Red and Black Trees yet, so I need to learn! Learn!
class Solution {
public:
char firstUniqChar(string s) {
if(s.empty()) return ' ';
unordered_map<char,int> m;
vector<char> vec;
for(char c:s){
if(m.count(c)) m[c]++;
else{
vec.push_back(c);
m[c]=1;
}
}
for(int i=0;i<vec.size();i++){
if(m[vec[i]]==1) return vec[i];
}
return ' ';
}
};