Original blog post, please indicate the source for reprinting!
This topic Niuke network address
The github address of the code in the blog post
1. Topic
2. Ideas
Build a hash table and count the number of occurrences of each character when scanning the string for the first time. The second time the string is scanned, the position of the first character that occurs only once is returned.
3. Code
1 class Solution { 2 public : 3 int FirstNotRepeatingChar( string str) { 4 5 // special input 6 if (str.size() == 0) return -1; 7 8 // auxiliary container 9 map< char , int > item; 10 11 // first traversal of string 12 for ( int i = 0; i < length; i++) 13 item[str[i]]++; 14 15 // second traversal of string 16 for (int i = 0; i < length; i++) 17 if (item[str[i]] == 1) 18 return i; 19 20 // no one-occurrence character 21 return -1; 22 } 23 };