LeetCode 题解工作台

查找共用字符

给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符 ),并以数组形式返回。你可以按 任意顺序 返回答案。 示例 1: 输入: words = ["bella","label","roller"] 输出: ["e","l","l"] 示例 2:…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们用一个长度为 的数组 记录每个字符在所有字符串中出现的最小次数,最后遍历 数组,将出现次数大于 的字符加入答案即可。 时间复杂度 $O(n \sum w_i)$,空间复杂度 。其中 为字符串数组 的长度,而 为字符串数组 中第 个字符串的长度,另外 为字符集的大小,本题中 $|\Sigma| = 26$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符(包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。

 

示例 1:

输入:words = ["bella","label","roller"]
输出:["e","l","l"]

示例 2:

输入:words = ["cool","lock","cook"]
输出:["c","o"]

 

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] 由小写英文字母组成
lightbulb

解题思路

方法一:计数

我们用一个长度为 2626 的数组 cntcnt 记录每个字符在所有字符串中出现的最小次数,最后遍历 cntcnt 数组,将出现次数大于 00 的字符加入答案即可。

时间复杂度 O(nwi)O(n \sum w_i),空间复杂度 O(Σ)O(|\Sigma|)。其中 nn 为字符串数组 wordswords 的长度,而 wiw_i 为字符串数组 wordswords 中第 ii 个字符串的长度,另外 Σ|\Sigma| 为字符集的大小,本题中 Σ=26|\Sigma| = 26

1
2
3
4
5
6
7
8
9
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())
speed

复杂度分析

指标
时间O(n \cdot k)
空间O(1)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

查找共用字符题解:数组·哈希·扫描 | LeetCode #1002 简单