Literally just iterate through all the letters in each word of words and append the index to the end of ans when word[i] == x.
code
class Solution {
public:
vector<int> findWordsContaining(vector<string>& words, char x) {
vector<int> ans;
for (int i = 0; i < words.size(); ++i) {
for (char& c : words[i]) {
if (c == x) {
ans.push_back(i);
break;
}
}
}
return ans;
}
};
complexity
- Time:
O(n * m)wherenis the size ofwordsandmis the length of the longest word insidewords- Space:
O(1)
time taken
- 1 minutes and 10 seconds