Leetcode 2942. Find Words Containing Character
You are given an array of strings words and a character ch. A string in words is considered containing ch if the character is present in the string.
Return an array of all the strings in words that contain the character ch.
words guaranteed to be a non-empty array of strings?ch be any valid character including whitespace and special characters?ch?words?ch is not present in any string within words.words and for each word, check if ch is present.ch is found in the word, include it in the result list.ch.n is the number of words in the list and m is the average length of the words. This complexity arises because we may need to check each character of each word.p is the total length of the words that contain the character ch.#include <vector>
#include <string>
using namespace std;
vector<string> findWordsContainingCharacter(vector<string>& words, char ch) {
vector<string> result;
for (const string& word : words) {
// Check if the character `ch` is in the word
if (word.find(ch) != string::npos) {
result.push_back(word);
}
}
return result;
}
Here’s a breakdown of the code:
word.find(ch) != string::npos checks if the character ch is present in the word.ch is found in the word, it is added to the result list.result list containing all words that have the character ch.This approach ensures that we efficiently filter out the required words while maintaining simplicity and readability.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?