阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述: 给定字符串 text,使用其中字母拼凑单词 balloon,每个字母只能使用一次,求最多能拼凑出多少个。 单词 balloon 字母构成:b、a、ll、oo、n,其中 l、o 每个气球需要2个,其余字母各1个。
示例:
输入:text = "nlaebolko" 输出:1 解释:每种关键字母数量仅够组成1个 balloon。
b,a,l,o,n 五个字母的出现次数;package lc1189;
import java.util.HashMap;
class Solution {
public int maxNumberOfBalloons(String text) {
HashMap<String, Integer> map = new HashMap<>();
for (char c : text.toCharArray()) {
String s = String.valueOf(c);
map.put(s, map.computeIfAbsent(s, k -> 0) + 1);
}
int res = map.getOrDefault("a", 0);
if (map.getOrDefault("b", 0) < res) {
res = map.getOrDefault("b", 0);
}
if (map.getOrDefault("l", 0) / 2 < res) {
res = map.getOrDefault("l", 0) / 2;
}
if (map.getOrDefault("o", 0) / 2 < res) {
res = map.getOrDefault("o", 0) / 2;
}
if (map.getOrDefault("n", 0) < res) {
res = map.getOrDefault("n", 0);
}
return res;
}
}class Solution {
public int maxNumberOfBalloons(String text) {
// cache[0]存储目标字符ASCII码,cache[1]存储对应计数
final int[][] cache = new int[2][5];
cache[0][0] = 97; // a
cache[0][1] = 98; // b
cache[0][2] = 108; // l
cache[0][3] = 110; // n
cache[0][4] = 111; // o
// 遍历字符串,仅统计balloon需要的5个字母
for (char ch : text.toCharArray()) {
final int intValue = ch;
for (int i = 0; i < 5; i++) {
if (intValue == cache[0][i]) {
cache[1][i]++;
break;
}
}
}
// l和o每个气球需要2个,计数整除2
cache[1][2] /= 2;
cache[1][4] /= 2;
// 遍历计数数组,取最小值,消除多层if判断
int min = Integer.MAX_VALUE;
for (int frequency: cache[1]) {
min = Math.min(min, frequency);
}
return min;
}
}balloon 中 l、o 各需要两个,必须整除2再参与比较。