leetcode
leetcode 2501 ~ 2550
查找包含给定字符的单词

查找包含给定字符的单词

难度:

标签:

题目描述

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非常大或单词长度非常长时,使用列表推导可能会导致内存错误。是否有其他内存效率更高的方法来处理此问题?
当处理非常大的数据时,使用列表推导可能会消耗大量内存,因为它会一次性生成一个完整的列表。为了提高内存效率,可以使用生成器表达式代替列表推导。生成器表达式不会一次性生成所有结果,而是按需生成每个结果,从而节省内存。在函数中,可以返回一个生成器对象而非列表,或者逐个处理并输出结果。例如: python class Solution: def findWordsContaining(self, words: List[str], x: str) -> Iterator[int]: return (i for i in range(len(words)) if x in words[i]) 这样调用者可以通过迭代返回的生成器来逐个获取结果,而不是一次性加载到内存中。
🦆
题解未考虑字符x不在任何单词中的情况,这是否会影响函数输出或应该在实现中考虑这种情况?
在当前的实现中,如果字符 `x` 不在任何单词中,列表推导式将不会找到任何匹配项,因此返回一个空列表。这本身就是一个合理的行为,因为它正确地表示没有单词包含给定的字符。通常,返回空列表是处理此类情况的有效方法,因为它既明确又能够通过返回值的长度给调用者正确的信号。因此,不需要额外的逻辑来特别处理这种情况。
🦆
如果字符x是特殊字符或有大小写敏感的需求,题解的方法是否需要调整?
如果需要处理特殊字符或考虑大小写敏感的情况,可以在检查 `x` 是否在单词中之前添加相应的处理逻辑。例如,如果需要忽视大小写,可以在比较之前将单词和字符 `x` 都转换为同样的大小写形式(全部大写或全部小写)。对于特殊字符,根据具体需求可能需要进行适当的转义或编码。示例代码如下: python class Solution: def findWordsContaining(self, words: List[str], x: str) -> List[int]: x = x.lower() # 将搜索字符转换为小写 return [i for i in range(len(words)) if x in words[i].lower()] # 同时将单词转换为小写进行比较 这种方法使函数更加灵活且适应多种情况。

相关问题