Sword refers to Offer 50. The first character that appears only once (C++) ordered hash table

Find the first character that appears only once in the string s. If not, return a single space. s contains only lowercase letters.

Example:

s = "abaccdeff"
返回 "b"
s = "" 
返回 " "

limit:

0 <= length of s <= 50000

Ordered hash table

On the basis of the hash table, the key-value pairs in the ordered hash table are sorted according to the insertion order. Based on this, the search for the first "character with a number of 1" can be achieved by traversing the ordered hash table.

The hash table is de-duplicated, that is, the number of key-value pairs in the hash table ≤ the length of the string s. Therefore, compared with the hash table method, the number of loops in the second round of traversal is reduced. When the string is very long (a lot of repeated characters), this method is more efficient.

Complexity analysis:

Time complexity O(N): N is the length of string s; need to traverse s two rounds, using O(N); vector search operation complexity is O(1);
space complexity O(1): due to the problem Point out that s only contains lowercase letters, so there are at most 26 different characters, and vector storage requires O(26) = O(1) extra space.

Since C++ does not provide its own chained hash table, a vector is used to store the keys in the hash table dic in order, and this vector can be traversed in the second round.

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

Insert picture description here

class Solution {
    
    
public:
    char firstUniqChar(string s) {
    
    
        vector<char> keys;//存放字母的数组
        unordered_map<char, bool> dic;//存放判断的哈希表
        for(char c : s) {
    
    
            if(dic.find(c) == dic.end())//若C不存在于dic里面
            //则,加进来keys
                keys.push_back(c);
            dic[c] = dic.find(c) == dic.end();//若dic.find(c) == dic.end()成立,
            //则dic[c] = true;若C已经在前面出现过,C就是出现在dic;
            //因此,则dic[c] = false
        }
        for(char c : keys) {
    
    
            if(dic[c]) return c;
        }
        return ' ';
    }
};

Author: jyd
link: https: //leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/solution/mian-shi-ti-50 -di-yi-ge-zhi-chu-xian-yi-ci-de-zi-3/
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114703145