题目描述
自己解法
由题意可知,字母的顺序并不重要,只需要比较词汇表
每个字符串中的每个字符的数目与字母表
中字符的数目即可,使用哈希表
即可求解,
Python3代码:
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
char_dict = {}
ans = 0
Is_correct = True
for val in chars:
if val in char_dict.keys():
char_dict[val] += 1
else:
char_dict[val] = 1
for word in words:
word_dict = {}
for char in word:
if char in word_dict.keys():
word_dict[char] += 1
else:
word_dict[char] = 1
for key in word_dict.keys():
Is_correct = True
if key not in char_dict.keys() or word_dict[key] > char_dict[key]:
Is_correct = False
break
if Is_correct:
ans += len(word)
return ans
时间复杂度为 O ( n ) O(n) O(n), n n n为词汇表中字符串总长度;空间复杂度为 O ( S ) O(S) O(S), S S S为字母表长度。
官方解答
思路一样,代码更为简洁,写法也很奇葩:
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
chars_cnt = collections.Counter(chars)
ans = 0
for word in words:
word_cnt = collections.Counter(word)
for c in word_cnt:
if chars_cnt[c] < word_cnt[c]:
break
else:
ans += len(word)
return ans
题解区解答:
膜拜一下大佬简洁的代码。。
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
ans = 0
cnt = collections.Counter(chars)
for w in words:
c = collections.Counter(w)
if all([c[i] <= cnt[i] for i in c]):
ans += len(w)
return ans