查找包含给定字符的单词
难度:
标签:
题目描述
You are given a 0-indexed array of strings words
and a character x
.
Return an array of indices representing the words that contain the character x
.
Note that the returned array may be in any order.
Example 1:
Input: words = ["leet","code"], x = "e" Output: [0,1] Explanation: "e" occurs in both words: "leet", and "code". Hence, we return indices 0 and 1.
Example 2:
Input: words = ["abc","bcd","aaaa","cbc"], x = "a" Output: [0,2] Explanation: "a" occurs in "abc", and "aaaa". Hence, we return indices 0 and 2.
Example 3:
Input: words = ["abc","bcd","aaaa","cbc"], x = "z" Output: [] Explanation: "z" does not occur in any of the words. Hence, we return an empty array.
Constraints:
1 <= words.length <= 50
1 <= words[i].length <= 50
x
is a lowercase English letter.words[i]
consists only of lowercase English letters.
代码结果
运行时间: 20 ms, 内存: 16.6 MB
/*
* 题目思路:
* 使用 Java Stream API 实现上述题目。
* 我们可以利用 Stream 的 filter 方法来筛选出包含字符 x 的字符串,
* 然后用 map 方法获取其下标,并最终收集为数组。
*/
import java.util.Arrays;
public class Solution {
public int[] findIndices(String[] words, char x) {
return IntStream.range(0, words.length)
.filter(i -> words[i].indexOf(x) != -1)
.toArray();
}
}
解释
方法:
题解通过使用列表推导来遍历字符串数组 `words`,对于每一个索引 `i` 和对应的单词,检查字符 `x` 是否存在于该单词中。如果存在,就将索引 `i` 添加到结果列表中。这种方法直接利用了 Python 的 `in` 关键字来进行成员检查,因此非常简洁且易于理解。
时间复杂度:
O(n * m)
空间复杂度:
O(n)
代码细节讲解
🦆
在某些特定情况下,如数组words非常大或单词长度非常长时,使用列表推导可能会导致内存错误。是否有其他内存效率更高的方法来处理此问题?
▷🦆
题解未考虑字符x不在任何单词中的情况,这是否会影响函数输出或应该在实现中考虑这种情况?
▷🦆
如果字符x是特殊字符或有大小写敏感的需求,题解的方法是否需要调整?
▷