题目:
给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)。
字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。
示例 1:
输入:text = "nlaebolko"
输出:1
示例 2:
输入:text = "loonbalxballpoon"
输出:2
示例 3:
输入:text = "leetcode"
输出:0
提示:
1 <= text.length <= 10^4
text 全部由小写英文字母组成
链接:https://leetcode-cn.com/problems/maximum-number-of-balloons
思路:
1、遍历字符串,用一个字典存储 'b' 'a' 'l' 'o' 'n'的出现次数。然后将字典中 'l' 'o'的值除以2。则气球的最大数量等于字典中最小的值
Python代码:
class Solution(object):
def maxNumberOfBalloons(self, text):
"""
:type text: str
:rtype: int
"""
dt = {'b':0,
'a':0,
'l':0,
'o':0,
'n':0
}
for i in text:
if i in dt:
dt[i] += 1
dt['l'] /= 2
dt['o'] /= 2
return min(dt.values())
C++代码:
class Solution {
public:
int maxNumberOfBalloons(string text) {
map<char, int> dt = {
{'b',0},
{'a',0},
{'l',0},
{'o',0},
{'n',0}
};
for (char item : text){
if (dt.find(item)!=dt.end()){
dt[item] += 1;
}
}
dt['l'] /= 2;
dt['o'] /= 2;
int ret = dt['b'];
for (auto iter=dt.begin(); iter!=dt.end(); iter++){
ret = min(ret, iter->second);
}
return ret;
}
};
网友评论