zoukankan      html  css  js  c++  java
  • 【leetcode】1189. Maximum Number of Balloons

    题目如下:

    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.

    解题思路:题目很简单,求出text中b,a,l,o,n这五个字符的出现次数的最小值即可。但有两点需要注意,一是text必须同时包含这五个字符,而是l和o是要算双份。

    代码如下:

    class Solution(object):
        def maxNumberOfBalloons(self, text):
            """
            :type text: str
            :rtype: int
            """
            dic = {}
            char_list = ['b','a','l','o','n']
            res = float('inf')
            for i in text:
                if i not in char_list:
                    continue
                dic[i] = dic.setdefault(i,0) + 1
            if len(char_list) != len(dic):
                return 0
            for k,v in dic.iteritems():
                if k in ('l','o'):
                    res = min(res,v/2)
                else:
                    res = min(res,v)
            return res
            
  • 相关阅读:
    5、流程控制
    4、字典和元祖
    3、列表操作
    2、字符串和数据类型
    1.标识符练习
    使用xpath提取页面所有a标签的href属性值
    网页提取所有邮箱
    正则表达式
    提取包含QQ的文本为QQ邮箱
    python继承小demo
  • 原文地址:https://www.cnblogs.com/seyjs/p/11531987.html
Copyright © 2011-2022 走看看