给你一个字符串text
,你需要使用text
中的字母来拼凑尽可能多的单词 "balloon"(气球)。
字符串text
中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。
示例 1:
输入:text = "nlaebolko"
输出:1
示例 2:
输入:text = "loonbalxballpoon"
输出:2
示例 3:
输入:text = "leetcode"
输出:0
提示:
1 <= text.length <= 10^4
text
全部由小写英文字母组成
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
astr = "balloon"
adic = dict()
for char in astr:
if char not in adic.keys():
adic[char] = 1
else:
adic[char] += 1
bdic = dict()
for char in text:
if char in astr:
if char not in bdic.keys():
bdic[char] = 1
else:
bdic[char] += 1
print(adic)
print(bdic)
if len(adic.keys()) != len(bdic.keys()):
return 0
value = 10**4
for key in adic.keys():
value = min(value, bdic[key]//adic[key])
print(value)
return value
Java:
class Solution {
public int maxNumberOfBalloons(String text) {
Map<Character, Integer> map = new HashMap<>();
String a = "balon";
for(int i = 0; i < text.length(); i++)
{
Character c = text.charAt(i);
if(a.indexOf(c) != -1)
{
map.put(c, map.getOrDefault(c, 0) + 1);
}
}
if(map.size() < 5)
return 0;
map.compute('l', (k,v)->v/=2);
map.compute('o', (k,v)->v/=2);
int value = text.length();
for(Character c: a.toCharArray())
{
value = Math.min(value, map.get(c));
}
return value;
}
}
留言