Niuke.com brush questions | The first character that only appears once

Topic source: Niuke.com

programming connection

Topic description

Find the first character that occurs only once in a string (1<=string length<=10000, all composed of letters), and return its position

topic analysis;

Use map to record the number of times of each character, and return the position where the number of times is 1.

Code:

class Solution {
public:
    int FirstNotRepeatingChar(string str) {        
        map<char,int>map;
        for(auto it = str.begin();it!=str.end();map[*it++]++);
        for(auto it = str.begin();it !=str.end();it++)
        {
            if(map[*it] == 1)
                return it - str.begin();
        }        
        return -1;        
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325624974&siteId=291194637