classSolution: defcountConsistentStrings(self, allowed: str, words: List[str]) -> int: alpha_dict = {} ans = 0 for alpha in allowed: # 用个字典保存 allowed 中的字符,之后检索就能加快 alpha_dict[alpha] = 1 for word in words: for a in word: if a notin alpha_dict: ans -= 1 break ans += 1 return ans
上面是第一个版本,最猪的一个,用字典存,您完全把集合忘掉了是吗( 下面是换成集合的,其实没差啦(
1 2 3 4 5 6 7 8 9 10 11
classSolution: defcountConsistentStrings(self, allowed: str, words: List[str]) -> int: alpha_set = set(allowed) ans = 0 for word in words: for a in word: if a notin alpha_set: ans -= 1 break ans += 1 return ans
再甚就直接利用特性了:
1 2 3 4 5 6 7 8 9 10
classSolution: defcountConsistentStrings(self, allowed: str, words: List[str]) -> int: ans = 0 for word in words: for a in word: if a notin allowed: ans -= 1 break ans += 1 return ans