leetcode 1189. Maximum Number of Balloons 解法 python

一.问题描述

Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.

You can use each character in text at most once. Return the maximum number of instances that can be formed.

 

Example 1:

Input: text = "nlaebolko"
Output: 1

Example 2:

 

Input: text = "loonbalxballpoon"
Output: 2

Example 3:

Input: text = "leetcode"
Output: 0

 

Constraints:

  • 1 <= text.length <= 10^4
  • text consists of lower case English letters only.

二.解题思路

也是一道水题,可以用来熟悉以下字典操作和python语法

组成balloon需要1个b 1个a 2个l 2个o 1个n,因此只需要统计每个字符出现的次数最后去最小那个就是

balloon在text中的最大组成次数,具体来说

1.用字典记录text中balloon(即balon)每个字符出现的次数

注意的是:balloon中l和o需要两个,因此计算l和o组成balloon的时候需要/2

2.l和o出现次数除2

3.计算balon中在text里出现的最小值,balon中出现次数最少的那个值就是balloon在text中组成的最大次数

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

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

三.源码

class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        target='balloon'
        ch_num=dict.fromkeys(target,0)
        for ch in text:
            if ch in target:
                ch_num[ch]+=1
        ch_num['l']=int(ch_num['l']/2)
        ch_num['o']=int(ch_num['o']/2)
        return min(ch_num.values())

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值