[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

這道題給了一個字符串 text,問用其中的字符最多能組成多少個 ballon,每個字符最多使用一次。對於一道 Easy 的題目來說,並沒有太大的難度,就是考察了一個統計字符出現的次數的操作,用一個 HashMap 來建立每個字符和其出現次數之間的映射就可以了。balloon 中的字符 b,a,n 分別出現了一次,l和o出現了兩次,怎么算最多能拼成多個 balloon 呢,當然要找這些字符出現次數最少的那個,就像木桶盛水一樣,最短的那個板子決定了盛水總量。然后遍歷 balloon 中的每個字符,取其中的最小值,注意對於l和o字符要將次數除以2,因為它們分別都出現了2次,最終返回這個最小值即可,參見代碼如下:


class Solution {
public:
    int maxNumberOfBalloons(string text) {
        int res = INT_MAX;
        string balloon = "balloon";
        unordered_map<char, int> charCnt;
        for (char c : text) ++charCnt[c];
        for (char c : balloon) {
            if (c == 'l' || c == 'o') res = min(res, charCnt[c] / 2);
            else res = min(res, charCnt[c]);
        }
        return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1189


參考資料:

https://leetcode.com/problems/maximum-number-of-balloons/

https://leetcode.com/problems/maximum-number-of-balloons/discuss/382396/JavaPython-3-Count-solution-w-analysis.

https://leetcode.com/problems/maximum-number-of-balloons/discuss/382401/WithComments-StraightForward-Java-Simple-count-of-chars


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM