美文网首页
LeetCode 1189. Maximum Number of

LeetCode 1189. Maximum Number of

作者: LiNGYu_NiverSe | 来源:发表于2020-11-21 01:23 被阅读0次

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:

Example 1

Input: text = "nlaebolko"
Output: 1

Example 2:

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.

Solution1:

from collections import Counter
class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        ans = 0
        lookup = Counter(text)
        while (all([lookup["b"], lookup["a"], lookup["l"], lookup["o"], lookup["n"]])):
            for c in "balloon":
                if lookup[c]:
                    lookup[c] -= 1
                else:
                    return ans
            ans += 1
        return ans

This question is a typical dict/hashmap question. One solution is to count every letter we have in text. Then we use while loop to deduct each character in "balloon" until the any of them is not available to be deducted.
这个问题是典型的dict / hashmap问题。一种解决方案是数出text中的每个字母的个数。然后,我们使用while循环来减去“balloon”中的每个字符,直到它们中的任何一个无法再能被减去为止。

Solution 2:

class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        return min(text.count("b"), text.count("a"), text.count("o")//2, text.count("l")//2, text.count("n"))

Another solution is to similar, instead of using hashmap/dict, we can simply count every letter in text using str.count() and find the minimal count of each character of "balloon", as it is the upper bound of how many "balloon" we can form using letters we have . Just keep in mind that each "balloon" needs 2 "l" and 2 "o" at a time, so we need to divide them by 2.
另一个解决方案是类似的,但不是使用hashmap / dict,我们可以简单地使用str.count()计算文本中的每个字母,并找到“balloon”每个字符的最小计数,因为它将决定“balloon”能被组成的个数的上限。请记住,每个“气球”一次需要2个“ l”和2个“ o”,因此我们需要将它们除以2。

相关文章

网友评论

      本文标题:LeetCode 1189. Maximum Number of

      本文链接:https://www.haomeiwen.com/subject/drksiktx.html