题目
类型:哈希表
解题思路
根据题意模拟即可。
先统计 text 中与单词 balloon 相关的字符数量,由于一个单词需要消耗两个 l 和 o 字符,对其统计数量进行除 2 下取整,然后所有字符的最小出现次数即是能够凑成 balloon 的最大数量。
代码
class Solution {
public int maxNumberOfBalloons(String text) {
int[] cnts = new int[5];
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == 'b') cnts[0]++;
else if (c == 'a') cnts[1]++;
else if (c == 'l') cnts[2]++;
else if (c == 'o') cnts[3]++;
else if (c == 'n') cnts[4]++;
}
cnts[2] /= 2; cnts[3] /= 2;
int ans = cnts[0];
for (int i = 0; i < 5; i++) ans = Math.min(ans, cnts[i]);
return ans;
}
}