2942. Find Words Containing Character #1721
-
Topics: You are given a 0-indexed array of strings Return an array of indices representing the words that contain the character Note that the returned array may be in any order. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the indices of words in a given list that contain a specific character. The solution involves iterating through each word and checking if the character is present, then collecting the indices of those words. Approach
This approach efficiently checks each word for the presence of the character using a linear scan through the list of words, resulting in a time complexity of O(n*m), where n is the number of words and m is the maximum length of the words. This is efficient given the problem constraints. Let's implement this solution in PHP: 2942. Find Words Containing Character <?php
/**
* @param String[] $words
* @param String $x
* @return Integer[]
*/
function findWordsContaining($words, $x) {
$result = array();
foreach ($words as $index => $word) {
if (strpos($word, $x) !== false) {
array_push($result, $index);
}
}
return $result;
}
// Example 1:
$words1 = array("leet", "code");
$x1 = "e";
print_r(findWordsContaining($words1, $x1)); // Output: [0,1]
// Example 2:
$words2 = array("abc", "bcd", "aaaa", "cbc");
$x2 = "a";
print_r(findWordsContaining($words2, $x2)); // Output: [0,2]
// Example 3:
$words3 = array("abc", "bcd", "aaaa", "cbc");
$x3 = "z";
print_r(findWordsContaining($words3, $x3)); // Output: []
?> Explanation:
This solution efficiently handles the constraints and ensures that we correctly identify all words containing the specified character, returning their indices in any order. |
Beta Was this translation helpful? Give feedback.
We need to find the indices of words in a given list that contain a specific character. The solution involves iterating through each word and checking if the character is present, then collecting the indices of those words.
Approach
strpos
function. If the character is found, add the current index to the result array.This approach efficiently checks each word for the presence of the character using …