Leetcode 2255. Count Prefixes of a Given String
The problem you are asked to solve is:
Given a list of strings words
and a string s
, return the number of strings in words
that are prefixes of s
.
A string word
is a prefix of s
if s
starts with word
.
Before we start writing the code, let’s clarify the problem:
s
be empty? Yes, if s
is empty, no string can be a prefix of it, so the result should be 0.words
and s
? Assume the length of words
and the length of any string within it (including s
) can be up to 100.words
and s
? No, they can contain any valid lower-case English letters.words
list.s
using the substr
method or the compare
function.Here is the C++ code implementing the above strategy:
#include <vector>
#include <string>
int countPrefixes(std::vector<std::string>& words, std::string s) {
int count = 0;
for (const std::string& word : words) {
if (s.substr(0, word.size()) == word) {
count++;
}
}
return count;
}
The time complexity of this solution can be analyzed as follows:
n
be the number of strings in words
.m
be the average length of the strings in words
.substr
method operates in O(m) time, where m is the length of the prefix being checked.n
times.Hence, the overall time complexity is O(n * m), where n
is the size of the words
list, and m
is the average length of the strings in words
.
This solution is efficient for the given problem constraints.
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?