LeetCode 题解工作台

查找包含给定字符的单词

给你一个下标从 0 开始的字符串数组 words 和一个字符 x 。 请你返回一个 下标数组 ,表示下标在数组中对应的单词包含字符 x 。 注意 ,返回的数组可以是 任意 顺序。 示例 1: 输入: words = ["leet","code"], x = "e" 输出: [0,1] 解释: "e"…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

我们直接遍历字符串数组 中的每一个字符串 ,如果 在 中出现,就将 加入答案数组中。 遍历结束后,返回答案数组即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的字符串数组 words 和一个字符 x 。

请你返回一个 下标数组 ,表示下标在数组中对应的单词包含字符 x 。

注意 ,返回的数组可以是 任意 顺序。

 

示例 1:

输入:words = ["leet","code"], x = "e"
输出:[0,1]
解释:"e" 在两个单词中都出现了:"leet" 和 "code" 。所以我们返回下标 0 和 1 。

示例 2:

输入:words = ["abc","bcd","aaaa","cbc"], x = "a"
输出:[0,2]
解释:"a" 在 "abc" 和 "aaaa" 中出现了,所以我们返回下标 0 和 2 。

示例 3:

输入:words = ["abc","bcd","aaaa","cbc"], x = "z"
输出:[]
解释:"z" 没有在任何单词中出现。所以我们返回空数组。

 

提示:

  • 1 <= words.length <= 50
  • 1 <= words[i].length <= 50
  • x 是一个小写英文字母。
  • words[i] 只包含小写英文字母。
lightbulb

解题思路

方法一:遍历

我们直接遍历字符串数组 wordswords 中的每一个字符串 words[i]words[i],如果 xxwords[i]words[i] 中出现,就将 ii 加入答案数组中。

遍历结束后,返回答案数组即可。

时间复杂度 O(L)O(L),其中 LL 为字符串数组 wordswords 中所有字符串的长度和。忽略答案数组的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def findWordsContaining(self, words: List[str], x: str) -> List[int]:
        return [i for i, w in enumerate(words) if x in w]
speed

复杂度分析

指标
时间O(n * m)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Does the candidate correctly iterate through both the array and characters within each word?

  • question_mark

    Is the candidate returning the indices rather than the words themselves?

  • question_mark

    Does the solution handle cases where no words contain the target character?

warning

常见陷阱

外企场景
  • error

    Returning words instead of indices.

  • error

    Assuming the array or words are sorted and returning incorrect order.

  • error

    Missing cases where no words contain the character, resulting in null or incorrect output.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return words containing the character instead of their indices.

  • arrow_right_alt

    Count how many times the character occurs in each word and return those counts.

  • arrow_right_alt

    Find indices of words containing multiple specified characters simultaneously.

help

常见问题

外企场景

查找包含给定字符的单词题解:数组·string | LeetCode #2942 简单