题目

类型:哈希表
image.png

解题思路

根据题意模拟即可。

先统计 text 中与单词 balloon 相关的字符数量,由于一个单词需要消耗两个 l 和 o 字符,对其统计数量进行除 2 下取整,然后所有字符的最小出现次数即是能够凑成 balloon 的最大数量。

代码

  1. class Solution {
  2. public int maxNumberOfBalloons(String text) {
  3. int[] cnts = new int[5];
  4. for (int i = 0; i < text.length(); i++) {
  5. char c = text.charAt(i);
  6. if (c == 'b') cnts[0]++;
  7. else if (c == 'a') cnts[1]++;
  8. else if (c == 'l') cnts[2]++;
  9. else if (c == 'o') cnts[3]++;
  10. else if (c == 'n') cnts[4]++;
  11. }
  12. cnts[2] /= 2; cnts[3] /= 2;
  13. int ans = cnts[0];
  14. for (int i = 0; i < 5; i++) ans = Math.min(ans, cnts[i]);
  15. return ans;
  16. }
  17. }