LeetCode 题解工作台

“气球” 的最大数量

给你一个字符串 text ,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球) 。 字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon" 。 示例 1: 输入: text = "nlaebolko" 输出: 1 示例 2:…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

我们统计字符串 `text` 中每个字母出现的次数,然后将其中字母 `'o'` 和 `'l'` 的出现次数分别除以 2,这是因为单词 `balloon` 中字母 `'o'` 和 `'l'` 都出现了 2 次。 接着,我们遍历单词 `balon` 中的每个字母,统计每个字母在字符串 `text` 中出现的次数的最小值,这个最小值就是单词 `balloon` 在字符串 `text` 中出现的最大次数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)

字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"

 

示例 1:

输入:text = "nlaebolko"
输出:1

示例 2:

输入:text = "loonbalxballpoon"
输出:2

示例 3:

输入:text = "leetcode"
输出:0

 

提示:

  • 1 <= text.length <= 104
  • text 全部由小写英文字母组成

 

注意:本题与 2287. 重排字符形成目标字符串 相同。

lightbulb

解题思路

方法一:计数

我们统计字符串 text 中每个字母出现的次数,然后将其中字母 'o''l' 的出现次数分别除以 2,这是因为单词 balloon 中字母 'o''l' 都出现了 2 次。

接着,我们遍历单词 balon 中的每个字母,统计每个字母在字符串 text 中出现的次数的最小值,这个最小值就是单词 balloon 在字符串 text 中出现的最大次数。

时间复杂度 O(n)O(n),空间复杂度 O(C)O(C)。其中 nn 为字符串 text 的长度;而 CC 为字符集大小,本题中 C=26C = 26

1
2
3
4
5
6
7
class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        cnt = Counter(text)
        cnt['o'] >>= 1
        cnt['l'] >>= 1
        return min(cnt[c] for c in 'balon')
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate identifies the need for frequency counting of characters relevant to 'balloon'.

  • question_mark

    The candidate efficiently computes the minimum number of 'balloon' instances from the character frequencies.

  • question_mark

    The candidate optimizes space by using a fixed-size hash table for character counts.

warning

常见陷阱

外企场景
  • error

    Ignoring the fact that 'l' and 'o' appear twice in the word 'balloon'.

  • error

    Not updating the result if some characters are missing or not sufficient to form a 'balloon'.

  • error

    Using unnecessary data structures or overly complex approaches when a simple hash table suffices.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the string contains extra characters not relevant to the word 'balloon'?

  • arrow_right_alt

    What if the input string is much shorter than the word 'balloon'?

  • arrow_right_alt

    How would you approach the problem if it were required to form multiple words instead of just one?

help

常见问题

外企场景

“气球” 的最大数量题解:哈希·表·结合·string | LeetCode #1189 简单