LeetCode 1684. 统计一致字符串的数目

给你一个由不同字符组成的字符串 allowed 和一个字符串数组 words 。如果一个words中的字符串的每一个字符都在 allowed 中,就称这个字符串是 一致字符串 。

请你返回 words 数组中 一致字符串 的数目。

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

法一:将allowed放入哈希表:

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 < s.size(); ++i) {
                if (!allowedList[s[i]]) {
                    break;
                }
            }

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

        return consistentStringNum;
    }
};

法二:将allowed哈希存入一个int中,再将每个words中的词哈希存入int,原理与法一相同,节省空间:

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;
    }
};
posted @   epiphanyy  阅读(5)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示