leetcode string The first character that appears only once

THE

problem

solution

Code



/*
思路: 这种带次数的数组和字符串问题最好的方法就是采用hashtable去解决,如果条件限制比较多的话,就可以结合双指针去解决。

我们看这个问题发现其只是统计出现一次的字符, 一个hash+ 加逻辑判断就可以解决。 注意map 是有序的, 按照序列大小去排序了。 我们要用hash。

-  define hashtable , make all data into hash  table.
-   loop to search what value is equal 1  return 
*/


class Solution {
    
    
public:
   int FirstNotRepeatingChar(string str) {
    
    
       unordered_map<char,int> need;
       for(int i = 0; i < str.size(); i++){
    
    
           
           need[str[i]]++;
         
       }
       for(char c: str){
    
    
           
           if(need[c]==1){
    
    
               
               for(int i= 0;i<str.size();i++){
    
    
                   
                   if(str[i]==c) return i;
               }
           }
       }
       return -1;
       
   }
};










Summary and reflection

  1. Through this question, I understand the traversal of hash and map. The order in the map is arranged according to the key, so the order of direct traversal is different from the order of insertion. If you want to maintain the order, you can only find it by checking the size of the key. If you traverse by itself, the original order will not be stored.

Guess you like

Origin blog.csdn.net/liupeng19970119/article/details/114178295