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

自己的思路并不困难,通过遍历一遍字符串,将对应的字符填入哈希表,完成一次遍历后再次遍历字符串,返回第一个哈希表中对应为1的字符的索引。

class Solution {
public:
    int firstUniqChar(string s) 
    {
        unordered_map<char,int> good;
        char temp = s[0];
        int i = 0;
        while(s[i]!='\0')
        {
            good[s[i]]++;
            i++;
        }
        int j = 0;
        while(s[j]!='\0')
        {
            if(good[s[j]] == 1)
            {
                return j;
            }
            j++;
        }
        return -1;
    }
};

看到一个很巧妙的方法,遍历所有字符,如果该字符在串中第一个下表与最后一个下标不保持一致,则继续遍历,如果一致,则返回。

posted @ 2021-03-10 15:06  zhaohhhh  阅读(43)  评论(0)    收藏  举报