20.4.12 字符串中的第一个唯一字符 简单

时间复杂度O(n),空间复杂度O(n)

题目

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.
 
注意事项:您可以假定该字符串只包含小写字母。

解题、代码思路

  1. 其实没必要这样写,我也是写完之后才知道find_last_of()这函数,从后往前找某个字符,返回索引。
  2. 循环,第一次遇到该字符用map存起来索引+1(value=0来判断是不是第一次),第二次遇到,value改为-1;
  3. 遍历map,除去value=1的,取最小的作为result返回,若没有找到,返回-1。

代码

class Solution {
public:
    int firstUniqChar(string s) {
        if(s.length() == 0) return -1;

        int result = INT_MAX;
        map<char, int> record;
        for(int i = 0; i < s.length(); i++){
            if(record[s[i]] == -1) continue;
            else if(record[s[i]] == 0) record[s[i]] = i + 1;
            else record[s[i]] = -1;
        }
        
        bool flag = false;
        for(auto c:record)
            if(c.second!=-1 && c.second-1<result){
                flag = true;
                result=c.second-1;
            } 
        if(!flag) result=-1;
        return result;
    }
};
posted @ 2020-04-12 14:33  肥斯大只仔  阅读(119)  评论(0编辑  收藏  举报