python-leetcode-1160. 拼写单词

1160. 拼写单词 - 力扣(LeetCode)

可以用 Python 来解决这个问题。思路如下:

  1. 统计 chars 中每个字母的出现次数。

  2. 遍历 words 列表,检查每个单词是否可以由 chars 中的字母拼出(即单词中的每个字母数量不能超过 chars 中对应的数量)。

  3. 如果单词可以拼出,就累加它的长度。

代码实现如下:

from collections import Counter

def countCharacters(words, chars):
    char_count = Counter(chars)  # 统计 chars 中每个字母的个数
    total_length = 0
    
    for word in words:
        word_count = Counter(word)  # 统计 word 中每个字母的个数
        if all(word_count[char] <= char_count.get(char, 0) for char in word):
            total_length += len(word)  # 累加满足条件的单词长度
    
    return total_length

# 示例
words = ["cat", "bt", "hat", "tree"]
chars = "atach"
print(countCharacters(words, chars))  # 输出 6

解释:

  • Counter(chars) 统计 chars 中的字符出现次数,如 "atach"{'a': 2, 't': 1, 'c': 1, 'h': 1}

  • 遍历 words 中的每个单词,统计单词的字符频率,确保所有字符数量都在 chars 允许的范围内。

  • 如果符合条件,则累加单词长度。

这个方法的时间复杂度是 O(N*M),其中 Nwords 的长度,M 是单词的平均长度,适用于一般规模的数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值