天天看点

Leetcode刷题笔记题解(C++):387. 字符串中的第一个唯一字符

Leetcode刷题笔记题解(C++):387. 字符串中的第一个唯一字符

思路一:新建一个map<char,int>来记录字符串中每个字符出现的次数,char出现的次数

然后再遍历字符串,找到第一个对应次数为1的字符返回即可

代码如下:

class Solution {
public:
    int firstUniqChar(string s) {
        map<char,int>m;
        for(int i=0;i<s.length();i++){
            m.insert(make_pair(s[i],++m[s[i]]));
        }
        for(int i=0;i<s.length();i++){
            if(m[s[i]]==1) return i;
        }
        return -1;
    }
};
           

思路二:题目说明只有小写字母,可以新建一个大小为26的数组来记录出现的次数,字符对应的是下标(a--0,b--1),下标对应的数组值即为出现的次数。

class Solution {
public:
    int firstUniqChar(string s) {
        int nums[26]={0};
        for(int i=0;i<s.length();i++){
            nums[s[i]-'a']+=1;
        }
        for(int i=0;i<s.length();i++){
            if(nums[s[i]-'a']==1) return i;
        }
        return -1;
    }
};