题目:
给你一个由不同字符组成的字符串 allowed 和一个字符串数组 words 。如果一个字符串的每一个字符都在 allowed 中,就称这个字符串是 一致字符串 。
请你返回 words 数组中 一致字符串 的数目。
示例 1:
输入:allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
输出:2
解释:字符串 "aaab" 和 "baa" 都是一致字符串,因为它们只包含字符 'a' 和 'b' 。
示例 2:
输入:allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
输出:7
解释:所有字符串都是一致的。
示例 3:
输入:allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
输出:4
解释:字符串 "cc","acd","ac" 和 "d" 是一致字符串。
提示:
1 <= words.length <= 104
1 <= allowed.length <= 26
1 <= words[i].length <= 10
allowed 中的字符 互不相同 。
words[i] 和 allowed 只包含小写英文字母。
来源:力扣(LeetCode)
方法:
1.使用数组记录字符串和子串中 元素出现的个数,并比较两者出现次数,满足要求则 +1。
2.使用位运算,对于字符串中的字母,最多只要 26 个,一个int型存在 32 位,可以记录 32 个状态,所有可以使用位运算,每一位代表一个元素的出现,和前面一样,只是数组换成了int型数据
c++:
class Solution {
public:
int countConsistentStrings(string allowed, vector<string>& words) {
vector<int> cnt(26);
for (char &c : allowed) {
cnt[c - 'a']++;
}
int res = 0;
for (string &word : words) {
bool ok = true;
for (char &c : word) {
if (cnt[c - 'a'] == 0) {
ok = false;
break;
}
}
if (ok) res++;
}
return res;
}
};
c语言代码实现:
int countConsistentStrings(char * allowed, char ** words, int wordsSize){
bool all[26] = {0};
bool word[26] = {0};
for (int i = 0; i < strlen(allowed); i++)
{
all[allowed[i] - 'a'] = true;
}
int count = 0;
for (int i = 0; i < wordsSize; i++) {//遍历字典数组
memset(word, 0, sizeof(word));
for (int j = 0; j < strlen(words[i]); j++) {//记录每一个子串元素种类
word[words[i][j] - 'a'] = true;
}
bool flag = true;
for (int j = 0; j < 26; j++) {//比较当前子串与字符串
if(word[j] == true && all[j] == false)//不满足要求
{
flag = false;
break;
}
}
if(flag)//满足要求+1
count++;
}
return count;
}
简单介绍一下memset函数:
memset函数,我们一起来看一下,以下是msdn上对memset的阐述:
memset
Sets buffers to a specified character.
将缓冲区设定为指定字符。
void *memset( void *dest, int c, size_t count );
有3个参数
Routine Required Header Compatibility
需要的头文件
memset <memory.h> or <string.h> ANSI, Win 95, Win NT
For additional compatibility information, see Compatibility in the Introduction.
Libraries
LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version
Return Value
memset returns the value of dest.
Parameters
dest
Pointer to destination
c
Character to set
count
Number of characters
Remarks
The memset function sets the first count bytes of dest to the character c.
Example
测试用例
:
/* MEMSET.C: This program uses memset to
* set the first four bytes of buffer to "*".
*/
#include <memory.h>
#include <stdio.h>
void main( void )
{
char buffer[] = "This is a test of the memset function";
printf( "Before: %s\n", buffer );
memset( buffer, '*', 4 );
printf( "After: %s\n", buffer );
}
Output
Before: This is a test of the memset function
After: **** is a test of the memset function
Buffer Manipulation Routines
See Also _memccpy, memchr, memcmp, memcpy, _strnset