387. 字符串中的第一个唯一字符

力扣原题链接(点我直达)

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

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

第一版,自己写的,时间较慢

执行用时 :112 ms, 在所有 cpp 提交中击败了23.15%的用户

内存消耗 :13 MB, 在所有 cpp 提交中击败了80.42%的用户

int firstUniqChar(string s) {

    if (s.size() == 0) return -1;

    unordered_map<char, pair<int, int>> result;//字符,出现次数,索引号
    for (unsigned i = 0; i < s.size(); ++i) {

        result[s[i]].first += 1;
        result[s[i]].second += i;

        //if (result[s[i]].first >= 2) result.erase(s[i]);
    }

    int res = s.size()-1;

    bool isOnce= false;
    for (auto& a : result) {
        if (a.second.first == 1)
        {
            res = res > a.second.second ? a.second.second : res;
            isOnce = true;
        }
        //cout << a.first << " " << a.second.first << " " << a.second.second << endl;
    }

    if (isOnce)
        return res;
    else
        return -1;

}

第二版,看的别人的,快多了

执行用时 :32 ms, 在所有 cpp 提交中击败了91.92%的用户

内存消耗 :12.6 MB, 在所有 cpp 提交中击败了96.83%的用户

就26个字符,所以直接开辟26个空间,初值都为0

int firstUniqChar(string s) {

    int result[26] = { 0 };
    for (auto &i : s)
        result[i - 'a'] ++;//统计每个字母的出现次数,0就是‘a’,1就是‘b’
    for (int i = 0; i < s.size(); i++) {
        if (result[s[i] - 'a'] == 1)//找到第一个就可以
            return i;
    }
    return -1;

}

我的方法必须遍历所以的元素才能找出最小值,这个直接根据s中字母的出现的先后来看

第三版,看了第二版又改进的第一版,还是比较慢

执行用时 :84 ms, 在所有 cpp 提交中击败了39.24%的用户

内存消耗 :13.2 MB, 在所有 cpp 提交中击败了70.44%的用户

int firstUniqChar(string s) {
    unordered_map<char, pair<int, int>> result;//字符,出现次数,索引号
    for (unsigned i = 0; i < s.size(); ++i) {
        result[s[i]].first += 1;
        result[s[i]].second += i;
    }

    for (unsigned i = 0; i < s.size(); ++i) {
    
        if (result[s[i]].first == 1) 
            return result[s[i]].second;
    }
    return -1;

}