[LeetCode] 1189. Maximum Number of Balloons

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.

“气球” 的最大数量。

给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)。

字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-number-of-balloons
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题的思路不难,就是用 hashmap 统计。这里我给出两种实现,思路都是统计每个字母的出现次数。

时间O(n)

空间O(n)

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 题目总结

posted @   CNoodle  阅读(72)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示