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.
此題要算出給定字串最多可以組成幾個"balloon"單字。
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
balloon_dict = dict()
balloon_list = list("balon")
for i in balloon_list:
balloon_dict[i] = 0
for i in list(text):
if i == 'b' or i == 'a' or i == 'l' or i == 'o' or i == 'n':
balloon_dict[i] += 1
if balloon_dict[min(balloon_dict, key = balloon_dict.get)] == 0:
return 0
else:
min_l_o = min(balloon_dict['l'], balloon_dict['o'])
return min_l_o//2
後續內容移到這裡囉:https://ithelp.ithome.com.tw/users/20100009/ironman/2870
希望透過記錄解題的過程,可以對於資料結構及演算法等有更深一層的想法。
如有需訂正的地方歡迎告知,若有更好的解法也歡迎留言,謝謝。