leetcode 1160. Find Words That Can Be Formed by Character 解法 Python

一.问题描述

ou are given an array of strings words and a string chars.

A string is good if it can be formed by characters from chars (each character can only be used once).

Return the sum of lengths of all good strings in words.

 

Example 1:

Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: 
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

Example 2:

Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: 
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.

 

Note:

  1. 1 <= words.length <= 1000
  2. 1 <= words[i].length, chars.length <= 100
  3. All strings contain lowercase English letters only.

二.解题思路

对于每个word,遍历,对每个char判断该char是否在chars里和该char在word中的数量是否小于或等于在chars中的数量。

都满足的话迭代下一个char,如果全部ch都满足,则该word符合。

可以增加一个剪枝操作,如果word的长度大于chars的长度,那么一定不符合。

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我

欢迎大家一起套路一起刷题一起ac

三.源码

class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        len_chars=len(chars)
        rst=0
        for word in words:
            if len(word)>len_chars:continue
            Flag=1
            for ch in word:
                if  ch not in chars or chars.count(ch)<word.count(ch):
                    Flag=0
                    break
            rst+=Flag*len(word)
        return rst

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值