LeetCode 题解工作台
查找包含给定字符的单词
给你一个下标从 0 开始的字符串数组 words 和一个字符 x 。 请你返回一个 下标数组 ,表示下标在数组中对应的单词包含字符 x 。 注意 ,返回的数组可以是 任意 顺序。 示例 1: 输入: words = ["leet","code"], x = "e" 输出: [0,1] 解释: "e"…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
我们直接遍历字符串数组 中的每一个字符串 ,如果 在 中出现,就将 加入答案数组中。 遍历结束后,返回答案数组即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你一个下标从 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 <= 501 <= words[i].length <= 50x是一个小写英文字母。words[i]只包含小写英文字母。
解题思路
方法一:遍历
我们直接遍历字符串数组 中的每一个字符串 ,如果 在 中出现,就将 加入答案数组中。
遍历结束后,返回答案数组即可。
时间复杂度 ,其中 为字符串数组 中所有字符串的长度和。忽略答案数组的空间消耗,空间复杂度 。
class Solution:
def findWordsContaining(self, words: List[str], x: str) -> List[int]:
return [i for i, w in enumerate(words) if x in w]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n * m) |
| 空间 | O(1) |
面试官常问的追问
外企场景- 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?
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.