Leetcode第1684题:统计一致字符串的数目(Count the number of consistent strings)

解题思路

采用位运算的思路不太好理解。但思想就是根据allowed建立一个\(mask\),遍历words中的每个元素的每个字符c,查看\(mask\)的值是否为真。
如果存在就返回结果加一。
如果不存在就退出当前字符串的遍历,转向words中的下一个字符串。

核心代码如下:

int countConsistentStrings(string allowed, vector<string>& words) {
        bool mask[26] = {false};
        for (char& c : allowed) {
            mask[c - 'a'] = true;    // 'a' - 'a' == 0 ==> mask[0]
        }

        int ret = 0;
        for (string& s : words) {
            bool exist = true;
            for (char& c : s) {
                if (!mask[c-'a']) {
                    //s中有字符不存在于allowed中
                    exist = false;
                    break;
                }
            }
            ret += exist;    //true == 1
        }
        return ret;
    }
posted @ 2022-11-08 13:09  hql5  阅读(26)  评论(0)    收藏  举报