Leetcode 2185. Counting Words With a Given Prefix
You are given an array of strings words
and a string prefix
. You need to return the number of strings in words
that contain the prefix
.
Input: words = ["pay", "attention", "practice", "attend"], prefix = "at"
Output: 2
Explanation: There are two words that start with "at": "attention" and "attend".
1 <= words.length <= 100
1 <= words[i].length, prefix.length <= 100
words
array.prefix
using the std::string
member function substr
.prefix
.#include <iostream>
#include <vector>
#include <string>
int countWordsWithPrefix(const std::vector<std::string>& words, const std::string& prefix) {
int count = 0;
for (const std::string& word : words) {
if (word.substr(0, prefix.size()) == prefix) {
count++;
}
}
return count;
}
int main() {
std::vector<std::string> words = {"pay", "attention", "practice", "attend"};
std::string prefix = "at";
std::cout << "Number of words with the given prefix: " << countWordsWithPrefix(words, prefix) << std::endl;
return 0;
}
n
is the number of words.m
is the maximum length of a word or the prefix.This solution is efficient given the constraints provided. If the constraints were larger, optimization techniques such as Trie data structures could be considered.
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?