leetcode 1684. Count the number of consistent strings (2022.11.8)

[Title] 1684. Count the number of consistent strings

You are given a string allowed consisting of different characters and an array words a string. A string is said to be consistent if every character of the string is in allowed.

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

Example 1:

输入:allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
输出:2
解释:字符串 "aaab" 和 "baa" 都是一致字符串,因为它们只包含字符 'a' 和 'b' 。

Example 2:

输入:allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
输出:7
解释:所有字符串都是一致的。

Example 3:

输入:allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
输出:4
解释:字符串 "cc","acd","ac" 和 "d" 是一致字符串。

hint:

1 <= words.length <= 104
1 <= allowed.length <= 26
1 <= words[i].length <= 10
allowed 中的字符 互不相同 。
words[i] 和 allowed 只包含小写英文字母。

[Problem-solving ideas 1] Counting arrays

Array ID 1 of int[26]


[Problem-solving ideas 2] flags, masks

class Solution {
    
    
    public int countConsistentStrings(String allowed, String[] words) {
    
    
        int mask = 0;
        for (int i = 0; i < allowed.length(); i++) {
    
    
            char c = allowed.charAt(i);
            mask |= 1 << (c - 'a');
        }
        int res = 0;
        for (String word : words) {
    
    
            int mask1 = 0;
            for (int i = 0; i < word.length(); i++) {
    
    
                char c = word.charAt(i);
                mask1 |= 1 << (c - 'a');
            }
            if ((mask1 | mask) == mask) {
    
    
                res++;
            }
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/XunCiy/article/details/128157076