微信公众号:三木小小推[1]
系列:刷题之Python
如果你觉得该系列对你有帮助,欢迎点好看[2]
问题描述
给你一份『词汇表』(字符串数组) 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
所有字符串中都仅包含小写英文字母
解决方案
class Solution:
def countCharacters(self, words, chars):
count = 0
chars = list(chars)
res_chars = chars.copy()
flag = 1
for word in words:
for t in range(len(word)):
word_match = word[t]
if chars == []:
flag = 0
break
match_list = [i for i in range(len(chars)) if chars[i] == word_match]
if match_list == []:
flag = 0
break
chars.pop(match_list[0])
if flag == 1:
count += len(word)
chars = res_chars.copy()
flag = 1
return count
题目分析
一定要注意如果用了pop一定要注意之后再次利用原始变量时,应使用copy
此外循环内部最后一次运行时其指针不论条件是否成立,均已经达到len(arg)-1
欢迎订阅
下面是三木小小推的二维码,欢迎订阅呦~~


文章转载自三木小小推,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




