题目
给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 “balloon”(气球)。
字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 “balloon”。
示例
输入:text = “nlaebolko”
输出:1
输入:text = “loonbalxballpoon”
输出:2
输入:text = “leetcode”
输出:0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-number-of-balloons
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:模拟统计
Java实现1:哈希表
class Solution {
public int maxNumberOfBalloons(String text) {
Map<Character, Integer> map = new HashMap<>();
map.put('b', 0);
map.put('a', 0);
map.put('l', 0);
map.put('o', 0);
map.put('n', 0);
for (char c : text.toCharArray()) {
if (map.containsKey(c)) map.put(c, map.get(c) + 1);
}
int min = Integer.MAX_VALUE;
for (char key : map.keySet()) {
int var = 0;
if (key == 'l' || key == 'o') {
var = map.get(key) / 2;
} else {
var = map.get(key);
}
if (var < min) min = var;
}
return min;
}
}
Java实现2:数组
class Solution {
public int maxNumberOfBalloons(String text) {
int[] cnt = new int[5];//b a l o n
for (char c : text.toCharArray()) {
if (c == 'b') cnt[0]++;
else if (c == 'a') cnt[1]++;
else if (c == 'l') cnt[2]++;
else if (c == 'o') cnt[3]++;
else if (c == 'n') cnt[4]++;
}
cnt[2] /= 2;
cnt[3] /= 2;
int ans = Integer.MAX_VALUE;
for (int i : cnt) ans = Math.min(ans, i);
return ans;
}
}