Leetcode daily 20/03/17 拼写单词
拼写单词
-题目-
给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。
-示例1-
输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释:
可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
-示例2-
输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。
-提示-
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
所有字符串中都仅包含小写英文字母
-方法1-
- 对字母表建一个字典。如果一个单词被掌握,其字母必定在字典里,且每个字母的个数小于字典里对应字母的个数。
-ac代码-
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
if not words:
return 0
if not chars:
return 0
cat_str = ''
chars_dict = collections.Counter(chars)
for word in words:
chars_dict_ = copy.deepcopy(chars_dict)
flag = True
for char in word:
if chars_dict_[char] > 0:
chars_dict_[char] -= 1
else:
flag = False
break
if flag:
cat_str += word
return len(cat_str)
-复杂度-
- \(T(n) = O(词汇表词汇长度和)\)
- \(S(n) = O(字母表字母集合的长度)\)
-方法1·改-
- 和的方法1基本相同,但对每个单词也建立字典,直接比较词汇表字典和字母表字典对应字符的数量。动态修改掌握的单词的总长度
rst,而不是返回时len()。
-ac代码-
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
if not words or not chars:
return 0
rst = 0
chars_dict = collections.Counter(chars)
for word in words:
word_dict = collections.Counter(word)
for char in word:
if chars_dict[char] < word_dict[char]:
break
else:
rst += len(word)
return rst
-复杂度-
和方法一相同。
-笔记-
- python-笔记:
for else的else会被执行,如果遍历完成而不是因为break而退出循环。

浙公网安备 33010602011771号