这题虽然是简单题,但是想要比较轻松写出来还是不简单的,需要一些技巧,通过解析区的大神学到通过hash函数来解决字符串匹配问题。
hash函数关键代码如下
int hash[26]={0};
char *p=allowed;
while(*p!='\0'){
hash[(int)(*p-'a')]++;
本题解题思路是枚举法,借助hash函数来让words字符串中每个字符串与allowed中的字符进行比较,用led来表示是否匹配,count来记录数量。
具体代码如下:
int countConsistentStrings(char * allowed, char ** words, int wordsSize){
int hash[26]={0};
int count=0;
int led=0;
char *p=allowed;
while(*p!='\0'){
hash[(int)(*p-'a')]++;
p++;
}
for(int i=0;i<wordsSize;i++){
p=words[i];
while(*p){
if(hash[(int)(*p-'a')]){
p++;led=1;
}else{
led=0;break;
}
}
if(led==1){
count++;led=0;
}
}
return count;
}