Problem:given a string, find the first non-repeating character in it and return it ' s index. If it doesn ' t exist, return-1.
Example:
s = "Leetcode" return 0.s = "Loveleetcode", return 2.
The first idea is to open an alphabet counter, traverse the elements in string s, and count each letter with a counter. Finally, traversing s again, looking for a count of 1 characters and then returning its index. The solution code is as follows:
1 classSolution {2 Public:3 intFirstuniqchar (strings) {4 int*alphabet =NULL;5Alphabet =New int[ -]();6 for(inti =0; I < s.length (); i++)7 {8alphabet[int(S[i]-'a')]++;9 }Ten for(inti =0; I < s.length (); i++) One { A if(alphabet[int(S[i]-'a')] ==1) - { - returni; the } - } - return-1; - + - } +};
However, if the string is very long and two traversal is expensive, you can consider a traversal, record the number and index of each letter with a hash table, with the following code:
1 classSolution {2 Public:3 intFirstuniqchar (strings) {4unordered_map<Char, pair<int,int>>m;5 intIDX =s.length ();6 for(inti =0; I < s.length (); i++)7 {8m[s[i]].first++;9M[s[i]].second =i;Ten } One for(Auto &p:m) A { - if(P.second.first = =1) - { theIDX =min (idx, p.second.second); - } - } - returnIDX = = S.length ()? -1: idx; + } -};
Leetcode 387. First Unique Character in a String