iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
0
Software Development

LeetCode小試身手系列 第 14

【Day 14】#1189 - Maximum Number of Balloons

  • 分享至 

  • xImage
  •  

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


希望透過記錄解題的過程,可以對於資料結構及演算法等有更深一層的想法。
如有需訂正的地方歡迎告知,若有更好的解法也歡迎留言,謝謝。


上一篇
【Day 13】#200 - Number of Islands
系列文
LeetCode小試身手14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言