Leetcode 1160. Find Words That Can Be Formed by Characters

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1160. Find Words That Can Be Formed by Characters相关的知识,希望对你有一定的参考价值。

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Find Words That Can Be Formed by Characters

2. Solution

**解析:**Version 1,使用Counter统计字符出现的次数,然后进行比较。Version 2,直接使用字符串的count方法统计字符出现的次数进行比较。

  • Version 1
class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        candidates = Counter(chars)
        lengths = 0
        for word in words:
            good = True
            temp = Counter(word)
            for ch, num in temp.items():
                if ch not in candidates or temp[ch] - candidates[ch] > 0:
                    good = False
                    break
            if good:
                lengths += len(word)
        return lengths
  • Version 2
class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        lengths = 0
        for word in words:
            good = True
            for ch in word:
                if word.count(ch) > chars.count(ch):
                    good = False
                    break
            if good:
                lengths += len(word)
        return lengths

Reference

  1. https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/

以上是关于Leetcode 1160. Find Words That Can Be Formed by Characters的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 1160. Find Words That Can Be Formed by Characters

1160.Find Words That Can Be Formed By Characters

leetcode1160

1160. Find Words That Can Be Formed by Characters 拼写单词 (统计字母数量的常用方法)

LeetCode 1160. 拼写单词

拼写单词(leetcode 1160)