Leetcode 1961. Check If String Is a Prefix of Array
Given a string s
and an array of strings words
, determine if s
is a prefix string of words
. A string s
is a prefix string of words
if s
can be formed by concatenating the first k
strings in words
for some positive k
no larger than words.length
.
If s
is a prefix string of words
, return true
, otherwise return false
.
Example 1:
Input: s = "iloveleetcode", words = ["i","love","leetcode","apples"]
Output: true
Explanation:
s can be formed by concatenating "i", "love", and "leetcode".
Example 2:
Input: s = "iloveleetcode", words = ["apples","i","love","leetcode"]
Output: false
Explanation:
It is impossible to form "iloveleetcode" by concatenating some of the first `k` strings in `words`.
s
?words
array?words
array?s
or an empty words
array?k
strings in words
exceeds the length of s
?The strategy to solve this problem can be described as follows:
words
.words
array and keep appending each element to the concatenated string.s
.s
, return true
.s
, break out of the loop since it is no longer possible to match s
.s
, return false
.This strategy ensures that we are efficiently checking the prefix condition without unnecessary computations.
The overall time complexity of the approach is O(n * m)
, where:
n
is the number of strings in the words
array.m
is the maximum length of the strings in words
.
This accounts for the concatenation process and the comparison at each step.We now present the implementation in C++:
#include <vector>
#include <string>
bool isPrefixString(std::string s, std::vector<std::string>& words) {
std::string concatenated;
for (const auto& word : words) {
concatenated += word;
if (concatenated == s) {
return true;
}
if (concatenated.size() > s.size()) {
return false;
}
}
return false;
}
This implementation follows our outlined strategy:
concatenated
string.word
in words
, and append it to concatenated
.concatenated
matches s
or exceeds its length.By following this method, we efficiently determine if s
is a prefix of the words
array.
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?