一.问题描述
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())