LeetCode 题解工作台
可以输入的最大单词数
键盘出现了一些故障,有些字母键无法正常工作。而键盘上所有其他键都能够正常工作。 给你一个由若干单词组成的字符串 text ,单词间由单个空格组成(不含前导和尾随空格);另有一个字符串 brokenLetters ,由所有已损坏的不同字母键组成,返回你可以使用此键盘完全输入的 text 中单词的数目。…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们可以用哈希表或者一个长度为 的数组 来记录所有损坏的字母键。 然后,我们遍历字符串 中的每个单词 ,如果 中的某个字母 在 中出现过,那么说明这个单词无法输入,答案不需要加一,否则答案需要加一。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
键盘出现了一些故障,有些字母键无法正常工作。而键盘上所有其他键都能够正常工作。
给你一个由若干单词组成的字符串 text ,单词间由单个空格组成(不含前导和尾随空格);另有一个字符串 brokenLetters ,由所有已损坏的不同字母键组成,返回你可以使用此键盘完全输入的 text 中单词的数目。
示例 1:
输入:text = "hello world", brokenLetters = "ad" 输出:1 解释:无法输入 "world" ,因为字母键 'd' 已损坏。
示例 2:
输入:text = "leet code", brokenLetters = "lt" 输出:1 解释:无法输入 "leet" ,因为字母键 'l' 和 't' 已损坏。
示例 3:
输入:text = "leet code", brokenLetters = "e" 输出:0 解释:无法输入任何单词,因为字母键 'e' 已损坏。
提示:
1 <= text.length <= 1040 <= brokenLetters.length <= 26text由若干用单个空格分隔的单词组成,且不含任何前导和尾随空格- 每个单词仅由小写英文字母组成
brokenLetters由 互不相同 的小写英文字母组成
解题思路
方法一:数组或哈希表
我们可以用哈希表或者一个长度为 的数组 来记录所有损坏的字母键。
然后,我们遍历字符串 中的每个单词 ,如果 中的某个字母 在 中出现过,那么说明这个单词无法输入,答案不需要加一,否则答案需要加一。
遍历结束后,返回答案即可。
时间复杂度 ,空间复杂度 ,其中 是字符串 的长度,而 是字母表的大小,本题中 。
class Solution:
def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
s = set(brokenLetters)
return sum(all(c not in s for c in w) for w in text.split())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for the ability to optimize the checking of each word by using a set for fast membership testing.
- question_mark
Ensure the candidate mentions checking each word individually instead of attempting to process all letters in one go.
- question_mark
Evaluate whether the candidate understands early exit in the context of word validation to improve efficiency.
常见陷阱
外企场景- error
Not using a set for `brokenLetters`, resulting in inefficient checks.
- error
Failing to stop checking a word once a broken letter is found, leading to unnecessary operations.
- error
Misunderstanding the problem by trying to check all words at once instead of word-by-word.
进阶变体
外企场景- arrow_right_alt
What if the input contains a very large number of words? Optimizing the check for each word is crucial.
- arrow_right_alt
If the brokenLetters string is empty, the solution should immediately return the count of all words.
- arrow_right_alt
Consider the case where all letters in the brokenLetters string are present in a word, which would result in zero words typed.