A character first appeared only

[Problem] In one string (0 <= length of the string <= 10000, all of the alphabet) find a first character appears only once, and returns to its position, or -1 if not (the size of the need to differentiate write).

[Idea] using a hash_map for storing the number of each character , only traversed once, and then again traversed the entire string of each letter, obtain the corresponding letters from the words in hash_map, if a direct return.

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

 

Guess you like

Origin www.cnblogs.com/zhudingtop/p/11368751.html