1189. Maximum Number of Balloons*

1189. Maximum Number of Balloons*

https://leetcode.com/problems/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 <= 10^4
  • text consists of lower case English letters only.

C++ 实现 1

统计 text 里的每个字符的个数, 看它们能组成多少个 “balloon”.

我还在 LeetCode 的讨论区写了个回答: [C++] Easy To Understand Solution

class Solution {
public:
    int maxNumberOfBalloons(string text) {
        unordered_map<char, int> record;
        for (auto &c : text) record[c] ++;
        int count = 0, i = 0;
        string target = "balloon";
        while (true) {
            int idx = i % target.size();
            if (record[target[idx]] == 0) break;
            if (idx == target.size() - 1) count ++;
            record[target[idx]] --;
            ++ i;
        }
        return count;
    }
};

C++ 实现 2

看讨论区中很多答案是检查组成 “balloon” 的字符个数够不够, 取其中字符个数最小值.

class Solution {
public:
    int maxNumberOfBalloons(string text) {
        unordered_map<char, int> mm;
        for (auto &i : text) mm[i] += 1;
        return min(mm['b'], min(mm['a'], min(mm['l']/2, min(mm['o']/2, mm['n']))));
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值