跳至主要内容

387. 字符串中的第一个唯一字符

class Solution {
public:
    int firstUniqChar(string s) {
        map<char, pair<int, int>> tmp;
        for (int i = 0; i < s.length(); i++)
        {
            if (tmp.find(s[i]) != tmp.end())
            {
                tmp[s[i]].second++;
            }
            else
            {
                tmp[s[i]] = make_pair(i, 0);
            }
        }
       
        int ret = INT_MAX;
        for (map<char, pair<int, int>>::iterator it = tmp.begin(); it != tmp.end(); it++)
        {
            if (it->second.second == 0 && it->second.first < ret)
            {
                ret = it->second.first;
            }
        }
       
        return ret != INT_MAX?ret:-1;
    }
};

评论

此博客中的热门博文