Leetcode 1961. Check If String Is a Prefix of Array
You are given a string s
and an array of strings words
. You need to determine if s
is a prefix of the concatenation of all the strings in words
.
A string s
is a prefix of a string t
if t
starts with the string s
.
Example 1:
Input: s = "iloveleetcode", words = ["i","love","leetcode","apples"]
Output: true
Explanation:
s starts with "i".
s. then, equals "i"+"love" (i.e "ilove").
s. then, equals "i"+"love"+"leetcode" (i.e "iloveleetcode").
Example 2:
Input: s = "iloveleetcode", words = ["apples","i","love","leetcode"]
Output: false
Explanation:
s does not start with "apples".
s
and words
?
words
contain empty strings or s
be an empty string?
words
?
public class Solution {
public boolean isPrefixString(String s, String[] words) {
StringBuilder concatenated = new StringBuilder();
for (String word : words) {
concatenated.append(word);
// If concatenated string equals s up to its length, it is a prefix
if (concatenated.length() >= s.length()) {
return concatenated.toString().startsWith(s);
}
}
return false; // If loop completes and no match was found
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1:
String s1 = "iloveleetcode";
String[] words1 = {"i", "love", "leetcode", "apples"};
System.out.println(solution.isPrefixString(s1, words1)); // Output: true
// Example 2:
String s2 = "iloveleetcode";
String[] words2 = {"apples", "i", "love", "leetcode"};
System.out.println(solution.isPrefixString(s2, words2)); // Output: false
}
}
StringBuilder
to efficiently concatenate the strings from the words
array.words
array, appending them to the StringBuilder
.s
up to its length.s
, check if it starts with s
. If it does, return true
. If the concatenated string surpasses the length of s
without matching, it will return false
.false
.n
is the total length of all the strings in the words
array. The append
operation within the loop and the startsWith
method call are linear operations relative to their input sizes. Since we potentially iterate through all characters in words
and perform a prefix check, the overall complexity is linear.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?