LeetCode 题解工作台
查找共用字符
给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符 ),并以数组形式返回。你可以按 任意顺序 返回答案。 示例 1: 输入: words = ["bella","label","roller"] 输出: ["e","l","l"] 示例 2:…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们用一个长度为 的数组 记录每个字符在所有字符串中出现的最小次数,最后遍历 数组,将出现次数大于 的字符加入答案即可。 时间复杂度 $O(n \sum w_i)$,空间复杂度 。其中 为字符串数组 的长度,而 为字符串数组 中第 个字符串的长度,另外 为字符集的大小,本题中 $|\Sigma| = 26$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
words ,请你找出所有在 words 的每个字符串中都出现的共用字符(包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
示例 1:
输入:words = ["bella","label","roller"] 输出:["e","l","l"]
示例 2:
输入:words = ["cool","lock","cook"] 输出:["c","o"]
提示:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]由小写英文字母组成
解题思路
方法一:计数
我们用一个长度为 的数组 记录每个字符在所有字符串中出现的最小次数,最后遍历 数组,将出现次数大于 的字符加入答案即可。
时间复杂度 ,空间复杂度 。其中 为字符串数组 的长度,而 为字符串数组 中第 个字符串的长度,另外 为字符集的大小,本题中 。
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
cnt = Counter(words[0])
for w in words:
t = Counter(w)
for c in cnt:
cnt[c] = min(cnt[c], t[c])
return list(cnt.elements())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \cdot k) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Evaluate how well the candidate handles array scanning and hash lookups.
- question_mark
Watch for issues with efficiently tracking duplicates.
- question_mark
Look for the candidate’s ability to minimize space usage during implementation.
常见陷阱
外企场景- error
Failing to account for duplicate characters and incorrectly handling them.
- error
Using unnecessary extra space for storing counts that could be optimized.
- error
Overcomplicating the solution instead of utilizing efficient hash lookups.
进阶变体
外企场景- arrow_right_alt
What if the list of words contains only one string?
- arrow_right_alt
What if there are no common characters between the words?
- arrow_right_alt
How would you modify the solution if the words can contain uppercase characters?