weinan030416

导航

第一个不重复的字符

循环超时

class Solution {
public:
    int firstUniqChar(string s) {
        for(int i=0;i<s.size();i++)
        {
            bool ok=true;
            for(int j=0;j<s.size();j++)
            {
                if(j==i)    continue;
                if(s[i]==s[j])  ok=false;
            }
            if(ok)
            return i;
        }
        return -1;       
    }
};

哈希表

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<int, int> position;
        int n = s.size();
        for (int i = 0; i < n; ++i) {
            if (position.count(s[i])) {
                position[s[i]] = -1;
            }
            else {
                position[s[i]] = i;
            }
        }
        int first = n;
        for (auto [_, pos]: position) {
            if (pos != -1 && pos < first) {
                first = pos;
            }
        }
        if (first == n) {
            first = -1;
        }
        return first;
    }
};

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/first-unique-character-in-a-string/solution/zi-fu-chuan-zhong-de-di-yi-ge-wei-yi-zi-x9rok/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

posted on 2023-02-13 14:05  楠030416  阅读(11)  评论(0编辑  收藏  举报