题目描述
给你一个字符串 text
,你需要使用 text
中的字母来拼凑尽可能多的单词 “balloon”(气球)。
字符串 text
中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 “balloon”。
样例
输入:text = "nlaebolko"
输出:1
输入:text = "loonbalxballpoon"
输出:2
输入:text = "leetcode"
输出:0
限制
1 <= text.length <= 10^4
text
全部由小写英文字母组成
算法
(模拟) $O(n)$
- 求出每个字母出现的次数,然后找
b
,a
,l
,o
,n
哪个字母是瓶颈。
时间复杂度
- 仅遍历一次字符串,故时间复杂度为 $O(n)$。
空间复杂度
- 仅需要长度为常数的数组存储字母的出现次数,故空间复杂度为 $O(1)$。
C++ 代码
class Solution {
public:
int maxNumberOfBalloons(string text) {
vector<int> ch(26, 0), cnt(26, 0);
ch['b' - 'a'] = 1;
ch['a' - 'a'] = 1;
ch['l' - 'a'] = 2;
ch['o' - 'a'] = 2;
ch['n' - 'a'] = 1;
int ans = text.length();
for (char c : text)
cnt[c - 'a']++;
for (int i = 0; i < 26; i++)
if (ch[i] != 0)
ans = min(ans, cnt[i] / ch[i]);
return ans;
}
};