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

题目

代码

class Solution {
public:
    int firstUniqChar(string s) {
        std::map<char,int> table;
        //先用map存储,value是出现的次数
        for(int i=0;i<s.size();i++)
        {
            table[s[i]]++;
        }
        //从头开始遍历数组,如果发现它出现的次数为1,则返回
        for(int i=0;i<s.size();i++)
        {
            if(table[s[i]]==1)
                return i;
        }
        
        return -1; 
    }
};

思路

直接用map保存出现的次数,然后从字符串头开始遍历,第一个在map中值为1即为所求。

https://github.com/li-zheng-hao
原文地址:https://www.cnblogs.com/lizhenghao126/p/11053643.html