leetcode 5189. “气球” 的最大数量(C++、python)

人盡茶涼 提交于 2019-11-29 18:40:47

给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)

字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"

 

示例 1:

输入:text = "nlaebolko"
输出:1

示例 2:

输入:text = "loonbalxballpoon"
输出:2

示例 3:

输入:text = "leetcode"
输出:0

 

提示:

  • 1 <= text.length <= 10^4
  • text 全部由小写英文字母组成

C++

class Solution {
public:
    int maxNumberOfBalloons(string text) 
    {
        map<char,int> tmp;
        for(auto c:text)
        {
            tmp[c]++;
        }
        int res=min(tmp['a'],tmp['b']);
        res=min(res,tmp['n']);
        int res2=min(tmp['l']/2,tmp['o']/2);
        return min(res,res2);
    }
};

python

class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        tmp=['a','b','l','o','n']
        dic={}
        for s in text:
            if s in tmp:
                if s in dic:
                    dic[s]+=1
                else:
                    dic[s]=1
        if len(dic)<5:
            return 0
        else:
            res=min(dic['a'],dic['b'])
            res=min(res,dic['n'])
            res2=min(dic['l']//2,dic['o']//2)
            return min(res,res2)
        
        

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!