387. First Unique Character in a String (Easy)

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

Solution:

-1: not appeared -2: appear more than once

-1: appear only once

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

results matching ""

    No results matching ""