Skip to content

Latest commit

 

History

History

2942

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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.

Similar Questions:

Hints:

  • Use two nested loops.

Solution 1.

// OJ: https://leetcode.com/problems/find-words-containing-character
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    vector<int> findWordsContaining(vector<string>& A, char x) {
        vector<int> ans;
        for (int i = 0; i < A.size(); ++i) {
            if (A[i].find(x) != string::npos) ans.push_back(i);
        }
        return ans;
    }
};