一. 题目
-
题目
-
示例
二. 方法一
-
解题思路
- 将chars字符串转化为Map
- 然后遍历words, 统计每一个元素所包含的字符是否在Map中
- 如果不在, 则直接跳过
- 如果在, 则将Map中该字符的数量-1, 如果字符数量小于0, 则跳过
- 到这一步, 则说明该元素的所有字符都在Map中, 且数量小于等于Map中该字符的数量
- 累加满足的元素的长度, 最后返回即可
-
解题代码
def countCharacters(self, words: List[str], chars: str) -> int: map1 = {} count = 0 # 可按照方法三优化 # 因为这是我自己的思路写的, 所以就不做更改 for ele in chars: if ele not in map1: map1[ele] = 1 else: map1[ele] += 1 for ele in words: flag = True temp = map1.copy() for e in ele: if e in temp: temp[e] -= 1 if temp[e] < 0: flag = False break else: flag = False break if flag: count += len(ele) return count
-
分析
时间复杂度: O(mn), m:列表中元素的个数, n:列表中元素的平均长度
空间复杂度: O(n)
三. 方法二
-
解题思路
- 将列表中的元素和chars都转变为map
- 比较每个元素的字符是否都在chars中,
- 如果有字符不在, 则直接跳过该字符
- 如果都在, 则再比较元素字符个数是否小于或等于chars中相同元素的个数.
- 不满足则跳过, 满足累计其字符串长度
-
解题代码
def countCharacters(self, words: List[str], chars: str) -> int: map1, map2 = {}, {} flag = True count = 0 for ele in chars: if ele not in map1: map1[ele] = 1 else: map1[ele] += 1 for word in words: map2.clear() for ele in word: if ele not in map2: map2[ele] = 1 else: map2[ele] += 1 for key in map2.keys(): if key in map1.keys() and map2[key] <= map1[key]: flag = True else: flag = False break if flag: count += len(word) return count
-
分析
时间复杂度: O(mn)
空间复杂度: O(m + n)
四. 方法三: 方法二的优化(官方)
-
解题思路
- 解题思路和方法二是一样的, 但是调用了
collections.Counter()
方法, 使得代码更为简洁 - map中如果key不存在, 则查询到的value值为0, 所以不用额外判断key是否存在
- 解题思路和方法二是一样的, 但是调用了
-
解题代码
def countCharacters(self, words: List[str], chars: str) -> int: count = 0 chars_map = collections.Counter(chars) for word in words: word_map = collections.Counter(word) for key in word_map.keys(): if word_map[key] > chars_map[key]: break else: count += len(word) return count
-
分析
时间复杂度: O(mn)
空间复杂度: O(m + n)