LeetCode 题解工作台
拼写单词
给定一个字符串数组 words 和一个字符串 chars 。 如果字符串可以由 chars 中的字符组成(每个字符在 每个 words 中只能使用一次),则认为它是好的。 返回 words 中所有好的字符串的长度之和。 示例 1: 输入: words = ["cat","bt","hat","tre…
4
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以用一个长度为 的数组 统计字符串 中每个字母出现的次数。 然后遍历字符串数组 ,对于每个字符串 ,我们用一个长度为 的数组 统计字符串 中每个字母出现的次数,如果对于每个字母 ,$wc[c] \leq cnt[c]$,那么我们就可以用 中的字母拼写出字符串 ,否则我们无法拼写出字符串 。如果可以拼写出字符串 ,那么我们就将字符串 的长度加到答案中。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给定一个字符串数组 words 和一个字符串 chars。
如果字符串可以由 chars 中的字符组成(每个字符在 每个 words 中只能使用一次),则认为它是好的。
返回 words 中所有好的字符串的长度之和。
示例 1:
输入:words = ["cat","bt","hat","tree"], chars = "atach" 输出:6 解释: 可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。
示例 2:
输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr" 输出:10 解释: 可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。
提示:
1 <= words.length <= 10001 <= words[i].length, chars.length <= 100words[i]和chars中都仅包含小写英文字母
解题思路
方法一:计数
我们可以用一个长度为 的数组 统计字符串 中每个字母出现的次数。
然后遍历字符串数组 ,对于每个字符串 ,我们用一个长度为 的数组 统计字符串 中每个字母出现的次数,如果对于每个字母 ,,那么我们就可以用 中的字母拼写出字符串 ,否则我们无法拼写出字符串 。如果可以拼写出字符串 ,那么我们就将字符串 的长度加到答案中。
遍历结束后,即可得到答案。
时间复杂度 ,空间复杂度 。其中 为题目中所有字符串的长度之和;而 为字符集的大小,本题中 。
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
cnt = Counter(chars)
ans = 0
for w in words:
wc = Counter(w)
if all(cnt[c] >= v for c, v in wc.items()):
ans += len(w)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n + m * k) where n is the length of chars, m is the number of words, and k is the average word length. Space complexity is O(1) since the frequency map uses a fixed-size array of 26 for lowercase letters. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Pay attention to independent word checks to avoid overcounting characters.
- question_mark
Use a fixed-size hash table for character counting to optimize for repeated lookups.
- question_mark
Emphasize correctness over clever shortcuts; each word must validate against the chars map precisely.
常见陷阱
外企场景- error
Reusing chars counts across multiple words without resetting for each word.
- error
Neglecting words with repeated characters exceeding chars availability.
- error
Confusing word length sum with word count; only lengths of valid words matter.
进阶变体
外企场景- arrow_right_alt
Return the list of words that can be formed instead of the sum of lengths.
- arrow_right_alt
Allow unlimited reuse of characters from chars and sum lengths accordingly.
- arrow_right_alt
Modify chars dynamically to remove used characters permanently across words.