leetcode:387. First Unique Character in a String

版权声明:hiahiahia~ 打劫来的原创!!未经允许可随便转载。喜欢就拿去。最喜欢的极客信条:【May you do good and not evil. May you find forgiveness for yourself and forgive others. May you share freely,never taking more than you give.】此博仅为本菜鸟的草稿本! https://blog.csdn.net/hunter___/article/details/90199975

不要慌,搞懂题目先,

思路:

unordered_map 映射好,然后判断:

不过好像比大家的慢了好多,为什么呢?有什么更快的呢

class Solution {
public:
    int firstUniqChar(string s) {
        int len=s.length();
        unordered_map<int,int> mp;
        
        for(int i=0;i<len;i++)
        {
            auto idx=s[i]-'a';
            if(mp.count(idx)){//exist, ++the value
                mp.insert(pair<int,int>(idx,(mp[idx])++));
            }
            mp.insert(pair<int,int>(idx,1));//not exist,insert new
        }
        for(int i=0;i<len;i++){//find first non-repeating
            auto idx=s[i]-'a';
            if(mp[idx] <=1 ){
                return i;
            }
        }
        return -1;//none repeat
    }
};

没什么影响,几乎。

class Solution {
public:
    int firstUniqChar(string s) {
        int len=s.length();
        unordered_map<char,int> mp;
        
        for(int i=0;i<len;i++)
        {
            // auto idx=s[i]-'a';
            if(mp.count(s[i])){//exist, ++the value
                mp.insert(pair<char,int>(s[i],(mp[s[i]])++));
            }
            mp.insert(pair<char,int>(s[i],1));//not exist,insert new
        }
        for(int i=0;i<len;i++){//find first non-repeating
            // auto idx=s[i]-'a';
            if(mp[s[i]] <=1 ){
                return i;
            }
        }
        return -1;//none repeat
    }
};

看大佬们怎么写的:

缩小循环次数,一次循环记录多个有用数据,尝试一次判断出来。

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char, pair<int, int>> m;
        int idx = s.size();
        for (int i = 0; i < s.size(); i++) {
            m[s[i]].first++;
            m[s[i]].second = i;
        }
        for (auto &p : m) {
            if (p.second.first == 1) idx = min(idx, p.second.second);
        }
        return idx == s.size() ? -1 : idx;
    }
};

猜你喜欢

转载自blog.csdn.net/hunter___/article/details/90199975
今日推荐