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

题目:

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

示例:(只包含小写字符)

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

思路:

  用一个桶来保存出现的次数,在遍历一遍即可。

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

猜你喜欢

转载自www.cnblogs.com/manch1n/p/10320178.html