/** * Note: The returned array must be malloced, assume caller calls free(). / int…
- User
/**
- Note: The returned array must be malloced, assume caller calls free(). / int findWordsContaining(char** words, int wordsSize, char x, int* returnSize) {
} LeetCode Logo Problem List 0
avatar Premium Debugging... Debugging...
Run Description Editorial Editorial Solutions Solutions Submissions Submissions
Code Testcase Test Result Test Result 2942. Find Words Containing Character Easy Topics Companies Hint 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. Seen this question in a real interview before? 1/5 Yes No Accepted 161.5K Submissions 182K Acceptance Rate 88.7% Topics Companies Hint 1 Similar Questions Discussion (21)
Choose a type
Copyright ©️ 2024 LeetCode All rights reserved
355
21
C Auto
123456 /**
- Note: The returned array must be malloced, assume caller calls free(). / int findWordsContaining(char** words, int wordsSize, char x, int* returnSize) {
} Saved Case 1 Case 2 Case 3
words = ["leet","code"] x = "e" 1 ["leet","code"] "e" ["abc","bcd","aaaa","cbc"] "a" ["abc","bcd","aaaa","cbc"] "z"
Tag
- Assistant
To solve this problem, we need to iterate over each word in the
wordsarray and check if it contains the characterx. If it does, we store the index of that word in a result array. Finally, we return the result array and update thereturnSizeto reflect the number of indices found.Here's the complete code:
/** * Note: The returned array must be malloced, assume caller calls free(). */ int* findWordsContaining(char** words, int wordsSize, char x, int* returnSize) { int* result = (int*)malloc(sizeof(int) * wordsSize); int count = 0; for (int i = 0; i < wordsSize; i++) { char* word = words[i]; int found = 0; for (int j = 0; word[j] != '\0'; j++) { if (word[j] == x) { found = 1; break; } } if (found) { result[count] = i; count++; } } *returnSize = count; return result; }