【LetMeFly】2942.查找包含给定字符的单词:使用库函数完成 力扣题目链接:https://leetcode.cn/problems/find-words-containing-character/
给你一个下标从 0 开始的字符串数组 words 和一个字符 x 。
请你返回一个 下标数组 ,表示下标在数组中对应的单词包含字符 x 。
注意 ,返回的数组可以是 任意 顺序。
示例 1:
输入: words = ["leet","code"], x = "e"
输出: [0,1]
解释: "e" 在两个单词中都出现了:"lee t" 和 "code " 。所以我们返回下标 0 和 1 。
示例 2:
输入: words = ["abc","bcd","aaaa","cbc"], x = "a"
输出: [0,2]
解释: "a" 在 "a bc" 和 "aaaa " 中出现了,所以我们返回下标 0 和 2 。
示例 3:
输入: words = ["abc","bcd","aaaa","cbc"], x = "z"
输出: []
解释: "z" 没有在任何单词中出现。所以我们返回空数组。
提示:
1 <= words.length <= 50
1 <= words[i].length <= 50
x 是一个小写英文字母。
words[i] 只包含小写英文字母。
解题方法:模拟 遍历字符串数组中的每个字符串,如果字符串中包含字符x,则将字符串对应下标添加到答案数组中。
时间复杂度$O(\sum)$,其中$\sum$是字符数之和
空间复杂度$O(1)$,力扣函数返回值不计入空间复杂度
AC代码 C++ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution {public : vector<int > findWordsContaining (vector<string>& words, char x) { vector<int > ans; for (int i = 0 ; i < words.size (); i++) { if (words[i].find (x) != string::npos) { ans.push_back (i); } } return ans; } };
Python 1 2 3 4 5 6 7 8 9 10 11 ''' Author: LetMeFly Date: 2025-05-24 21:30:36 LastEditors: LetMeFly.xyz LastEditTime: 2025-05-24 21:37:05 ''' from typing import List class Solution : def findWordsContaining (self, words: List [str ], x: str ) -> List [int ]: return [i for i in range (len (words)) if x in words[i]]
Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import java.util.List;import java.util.ArrayList;class Solution { public List<Integer> findWordsContaining (String[] words, char x) { List<Integer> ans = new ArrayList <>(); for (int i = 0 ; i < words.length; i++) { if (words[i].indexOf(x) >= 0 ) { ans.add(i); } } return ans; } }
Go 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package mainimport "strings" func findWordsContaining (words []string , x byte ) (ans []int ) { for i, word := range words { if strings.IndexByte(word, x) >= 0 { ans = append (ans, i) } } return }
同步发文于CSDN 和我的个人博客 ,原创不易,转载经作者同意后请附上原文链接 哦~
千篇源码题解已开源