【LeetCode/力扣】#1160-拼写单词
作者:互联网
1 题目描述
题目链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/
给你一份『词汇表』(字符串数组) 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
所有字符串中都仅包含小写英文字母
2 代码/Python 3
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
ret = 0
chars_dic = {}
for i in chars: # chars转为字典,字符出现次数统计
chars_dic[i] = chars_dic.get(i,0) + 1
for word in words:
tem_dic = chars_dic.copy() # 拷贝chars生成的字典
for i in word:
if i in tem_dic:
tem_dic[i] -= 1
# 当word中字符不在字典或出现次数超过字典中的次数,则word无法拼写
if i not in tem_dic or tem_dic[i] < 0:
break
else:
ret += len(word) # 当for循环正常运行完成,则word可拼写,统计word长度
return ret
3 代码解释
在 Python 中,else 不仅可以与 if 搭配使用,还可以与 for 结合。
但 else 里面的语句不一定执行,取决于 for 循环能否正常执行完毕。如果 for 循环中有 break 字段等导致 for 循环没有正常执行完毕,那么 else 中的内容也不会执行;如果for循环正常执行完毕,那么else中的内容可以执行。
上述例子中,当word中每个字符都出现在chars中,且出现次数不大于chars中的次数,则for循环正常执行(不会执行到break),那么else里的长度累加可以执行。
标签:1160,tem,chars,dic,力扣,words,word,else,LeetCode 来源: https://blog.csdn.net/baidu_35231778/article/details/116453607