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

1 题目描述

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

2 示例描述

2.1 示例1

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

2.2 示例2

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

2.3 示例3

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

3 解题提示

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

4 解题思路

简单的一种暴力思路,用words里面的子串的长度来作为循环的次数,遍历allowed中的字符,判断是否相等,作为一个累加条件,后累加结果与子串长度对比,若相等,则表示只包含allowed中的字符。

5 代码详解

class Solution {
public:
int countConsistentStrings(string allowed, vector<string>& words) {
int ans = 0 ;
for ( int i = 0 ; i < words.size() ; i ++ )
{
int n = 0 ; //记录一个串内有几个字符是相等的,最后判断用
for ( int j = 0 ; j < words[i].size() ; j ++ )
{
for ( char c : allowed )
{
if ( c == words[i][j] )
{
n ++ ;
break ;
}
}
}
if ( n == words[i].size() )
{
ans ++ ;
}
}
return ans ;
}
};