【Leetcode387】First Unique Character in a String

class Solution {
public:
    int firstUniqChar(string s) {
        vector<int> v(26, -1);
        for(size_t index = 0; index < s.length(); ++index){
            if(v[s[index]-'a'] == -1){
                v[s[index]-'a'] = index;
            }else if(v[s[index]-'a'] >= 0){
                v[s[index]-'a'] = -2;
            }
        }
        int result = s.length();
        for(const auto& num : v){
            if(num >= 0 && num < result)
                result = num;
        }
        if(result == s.length())
            return -1;
        else
            return result;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章