力扣题目学习—拼写单词

给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。

在这里插入图片描述
代码一:

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

作者:smoon1989
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/solution/tong-ji-python3-by-smoon1989/

collections.Counter是统计列表元素出现次数。
在for循环中,w为每次循环的字符串,在例二中,第一次循环w为hello,第二次为world,第三次为leetcode。
第一次循环中,c是对“hello”这个字符串的每个单词的个数进行标注,例如c[0]就表示h值为1,c[1]就表示e值为1,c[2]就表示l值为2,c[3]就表示o值为1。

代码二:

class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        sum = 0
        for i in words:
            k = len(i)
            m = 0
            for j in i:
                if i.count(j) <= chars.count(j):
                    m += 1
            if m == k:
                sum += k
        return sum

作者:he-fang-yuan
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/solution/pin-xie-dan-ci-by-he-fang-yuan/

在第一次循环中i为“hello”字符串,k为字符串的长度为5。
在内循环中,j是i字符串中的每个字母。
对于第一个内循环,判断如果i字符串中,h字母出现的次数如果小于chars字符串中h字母出现的次数,则m自加1,以此循环。

发布了19 篇原创文章 · 获赞 0 · 访问量 405

猜你喜欢

转载自blog.csdn.net/MercuryG/article/details/104931404