【LeetCode】字符串中的第一个唯一字符

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

s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.

注意事项:您可以假定该字符串只包含小写字母。

【思路】首先建立一个26大小的数组,使用s[i]-'0'作为索引,一次遍历后,使用数组储存每个字符出现的次数。接着再对字符串进行一次遍历,然后根据字符去数组中查找相应的次数,如果第一次出现次数为1,则返回,否则返回-1.

class Solution {
public:
    int firstUniqChar(string s) {
        int len = s.size();
        if(len == 0)  return -1;
        vector<int> table(26, 0);
        for(int i = 0; i < len; i++){
            table[s[i] - 'a'] ++;
        }
        for(int i = 0; i < len; i++){
            if(table[s[i] - 'a'] == 1){
                return i;
            }
        }
        return -1;
    }
};

猜你喜欢

转载自www.cnblogs.com/zhudingtop/p/11735048.html