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

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

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

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

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

题目链接

哈希表

遍历判断即可。

class Solution {
public:
    map<char,int>allow;
    map<char,int>word;
    int res;
    int countConsistentStrings(string allowed, vector<string>& words) {
        res=0;
        for(auto ch:allowed)    allow[ch]=1;
        for(int i=0;i<words.size();i++){
            word.clear();
            for(auto ch:words[i])   word[ch]=1;
            char ch;
            int flag=0;
            for(ch='a';ch<='z';ch++){
                //cout<<ch<<" "<<allow[ch]<<" "<<word[ch]<<endl;
                if(word[ch]&&word[ch]!=allow[ch]){
                    flag=1;
                    break;
                }
            }
            //cout<<"last:"<<ch<<" "<<word[ch]<<" "<<allow[ch]<<endl;
            if(!flag)    res++;
        }
        return res;
    }
};
posted @ 2022-11-08 10:00  认真游泳的鱼  阅读(33)  评论(0)    收藏  举报