方法一 Set()+双层for循环遍历
将allowd放入Set集合中,遍历words每一项的每一个字符看是否有allowd不含有的字符
var countConsistentStrings = function(allowed, words) {
let set = new Set(allowed),count=0
for(let word of words){
for(let char of word){
if(!set.has(char)){
count--
break
}
}
count++
}
return count
};
消耗时间和内存情况:
方法二 Set+reduce() +every()
和方法一 一样的,写法不同
var countConsistentStrings = function(allowed, words) {
const set = new Set(allowed)
return words.reduce((count, word) => Array.from(word).every(c => set.has(c)) ? count + 1 : count, 0)
};
消耗时间和内存情况: