返回介绍

solution / 2900-2999 / 2942.Find Words Containing Character / README_EN

发布于 2024-06-17 01:02:58 字数 4091 浏览 0 评论 0 收藏 0

2942. Find Words Containing Character

中文文档

Description

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.

Solutions

Solution 1: Traversal

We directly traverse each string words[i] in the string array words. If x appears in words[i], we add i to the answer array.

After the traversal, we return the answer array.

The time complexity is $O(L)$, where $L$ is the sum of the lengths of all strings in the array words. Ignoring the space consumption of the answer array, the space complexity is $O(1)$.

class Solution:
  def findWordsContaining(self, words: List[str], x: str) -> List[int]:
    return [i for i, w in enumerate(words) if x in w]
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) != -1) {
        ans.add(i);
      }
    }
    return ans;
  }
}
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;
  }
};
func findWordsContaining(words []string, x byte) (ans []int) {
  for i, w := range words {
    for _, c := range w {
      if byte(c) == x {
        ans = append(ans, i)
        break
      }
    }
  }
  return
}
function findWordsContaining(words: string[], x: string): number[] {
  const ans: number[] = [];
  for (let i = 0; i < words.length; ++i) {
    if (words[i].includes(x)) {
      ans.push(i);
    }
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文