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.
Solution: HashTable
Use a hashtable to count the occurrence of each letter and find the bottleneck one.
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 |
// Author: Huahua class Solution { public: int maxNumberOfBalloons(string text) { map<char, int> c; for (char t : text) ++c[t]; return min({c['b'], c['a'], c['l'] / 2, c['o'] / 2, c['n']}); } }; |