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/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值