# [LeetCode] 1189. Maximum Number of Balloons

2021-09-15 02:05:08  阅读：19  来源： 互联网

Given a string `text`, you want to use the characters of `text` to form as many instances of the word "balloon" as possible.

You can use each character in `text` at most once. Return the maximum number of instances that can be formed.

Example 1:

```Input: text = "nlaebolko"
Output: 1
```

Example 2:

```Input: text = "loonbalxballpoon"
Output: 2
```

Example 3:

```Input: text = "leetcode"
Output: 0```

Constraints:

• `1 <= text.length <= 104`
• `text` consists of lower case English letters only.

“气球” 的最大数量。

Java实现一

``` 1 class Solution {
2     public int maxNumberOfBalloons(String text) {
3         HashMap<Character, Integer> map = new HashMap<>();
4         for (char c : text.toCharArray()) {
5             map.put(c, map.getOrDefault(c, 0) + 1);
6         }
7
8         int count = 0;
9         while (true) {
10             int countB = map.getOrDefault('b', 0);
11             int countA = map.getOrDefault('a', 0);
12             int countL = map.getOrDefault('l', 0);
13             int countO = map.getOrDefault('o', 0);
14             int countN = map.getOrDefault('n', 0);
15             if (countB >= 1 && countA >= 1 && countL >= 2 && countO >= 2 && countN >= 1) {
16                 count++;
17                 map.put('b', countB - 1);
18                 map.put('a', countA - 1);
19                 map.put('l', countL - 2);
20                 map.put('o', countO - 2);
21                 map.put('n', countN - 1);
22             } else {
23                 break;
24             }
25         }
26         return count;
27     }
28 }```

Java实现二

``` 1 class Solution {
2     public int maxNumberOfBalloons(String text) {
3         int[] map = new int[26];
4         for (char c : text.toCharArray()) {
5             map[c - 'a']++;
6         }
7         int min = map[1];                        // for b
8         min = Math.min(min, map[0]);            // for a
9         min = Math.min(min, map[11] / 2);        // for l /2
10         min = Math.min(min, map[14] / 2);        // similarly for o/2
11         min = Math.min(min, map[13]);            // for n
12         return min;
13     }
14 }```

LeetCode 题目总结