LeetCode 1684. Count the number of consistent strings

Give you a string of different characters allowed and a string array words. If every character of a string is in allowed, the string is said to be a consistent string.

Please return the number of consistent strings in the words array.

1 <= words.length <= 104
1 <= allowed.length <= 26
1 <= words[i].length <= 10
The characters in allowed are different.
words[i] and allowed only contain lowercase English letters.

Method 1: Put allowed into the hash table:

class Solution {
    
    
public:
    int countConsistentStrings(string allowed, vector<string>& words) {
    
    
        vector<bool> allowedList(256, false);

        for (char c : allowed) {
    
    
            allowedList[c] = true;
        }
       
        unsigned consistentStringNum = 0;
        for (string &s : words) {
    
    
            size_t i = 0;
            for ( ; i < words.size(); ++i) {
    
    
                if (!allowedList[s[i]]) {
    
    
                    break;
                }
            }

            if (i == s.size()) {
    
    
                ++consistentStringNum;
            }
        }

        return consistentStringNum;
    }
};

Method 2: Store the allowed hash in an int, and then hash the words in each word. The principle is the same as the method:

class Solution {
    
    
public:
    int Biterization(string &s) {
    
    
        int res = 0;
        for (char c : s) {
    
    
            res |=  (1 << c - 'a');
        }
        return res;
    }

    int countConsistentStrings(string allowed, vector<string>& words) {
    
    
        int allowBit = Biterization(allowed);

        unsigned consistentStringNum = 0;
        for (string &s : words) {
    
    
            int sBit = Biterization(s);
            if ((sBit | allowBit) == allowBit) {
    
    
                ++consistentStringNum;
            }
        }

        return consistentStringNum;
    }
};

Guess you like

Origin blog.csdn.net/tus00000/article/details/111416024