天天看点

【2019秋冬】【LeetCode】387 字符串中第一个唯一字符

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char,int> ti;
        for(int i=0; i<s.length(); i++){
            ti[s[i]]++;
        }
        for(int i=0; i<s.length(); i++){
            if(ti[s[i]]==1) return i;
        }
        return -1;
    }
};
           

用map还是时间长一些

也可以直接用数组,然后char-‘a’转数字,时间更短