LeetCode 809. (字符扩张后至少为 3)情感丰富的文字(Medium)

在这里插入图片描述
【题目链接】

题解

  1. 情感丰富的文字

思路

  • 需要灵活使用Python自带的内置函数(zip、all、any等)和工具函数(itertools等)
    在这里插入图片描述

代码

class Solution:
    def expressiveWords(self, S: str, words: List[str]) -> int:
        # 使用zip函数,将字符串拆分为字符部分和对应的字符计数部分
        def get_charLs_and_cntLs(s):
            if s == '': # 若字符串为空则返回2个空列表
                return [], []

			# 使用zip打包,使用zip(*)来解压
            zipped = [(char, len(list(group))) for char, group in itertools.groupby(s)] 
            return zip(*zipped)

        tar_chars, tar_cnts = get_charLs_and_cntLs(S)

        cnt = 0
        for word in words:
            can_chars, can_cnts = get_charLs_and_cntLs(word)

			# 若候选字符串的字符集合和目标字符串的字符集合不相同,则此候选字符串不是可扩张的
            if tar_chars != can_chars: continue

            # 若每一位:目标字符计数都大于等于候选字符计数与3的最大值 或者 目标字符计数与候选字符计数相同,
            # 则此候选字符串是可扩张的,则计数器加一(使用all函数来判断是否每一位都满足条件)
            # 灵活使用zip来打包
            cnt += all([tar_cnt >= max(can_cnt, 3) or tar_cnt == can_cnt for 
            		tar_cnt, can_cnt in zip(tar_cnts, can_cnts)]) 
        
        return cnt
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值