美文网首页Leetcode
Leetcode.387.FIrst Unique Charac

Leetcode.387.FIrst Unique Charac

作者: Jimmy木 | 来源:发表于2020-01-06 10:26 被阅读0次

题目

给定一个字符串, 字符串只包含小写字母. 找出字符串第一个不重复的字符索引, 找不到返回-1.

Input:  "leetcode"
Output: 0 
Input:  "loveleetcode"
Output: 2

思路

先遍历一次,找出每个字符的出现次数. 遍历第二次输出结果.

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

总结

加入不是只包含小写字母, 就需要使用map. 本题使用数组明显速度和内存都更优.

相关文章

网友评论

    本文标题:Leetcode.387.FIrst Unique Charac

    本文链接:https://www.haomeiwen.com/subject/nrihactx.html