1189. Maximum Number of Balloons*
原创
©著作权归作者所有:来自51CTO博客作者珍妮的选择的原创作品,请联系作者获取转载授权,否则将追究法律责任
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']))));
}
};