LeetCode 1961: Check If String Is a Prefix of Array Solution
Master LeetCode problem 1961 (Check If String Is a Prefix of Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1961. Check If String Is a Prefix of Array
Problem Explanation
Explanation:
To solve this problem, we can iterate through the array of words and concatenate them one by one until the concatenated string matches the input string s. If at any point the concatenated string becomes longer than s, we can immediately return false. If the concatenated string matches s, we return true.
-
Algorithm:
- Initialize an empty string
concatenated. - Iterate through the array of words.
- For each word, concatenate it to the
concatenatedstring. - Check if the
concatenatedstring matches the input strings. - If the
concatenatedstring matchess, returntrue. - If the
concatenatedstring becomes longer thans, returnfalse. - Return
falseat the end if no match is found.
- Initialize an empty string
-
Time Complexity: O(N) where N is the total number of characters in the input string
sand all words in the array. -
Space Complexity: O(N) for the
concatenatedstring.
:
Solution Code
class Solution {
public boolean isPrefixString(String s, String[] words) {
String concatenated = "";
for (String word : words) {
concatenated += word;
if (concatenated.equals(s)) {
return true;
}
if (concatenated.length() > s.length()) {
return false;
}
}
return false;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1961 (Check If String Is a Prefix of Array)?
This page provides optimized solutions for LeetCode problem 1961 (Check If String Is a Prefix of Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1961 (Check If String Is a Prefix of Array)?
The time complexity for LeetCode 1961 (Check If String Is a Prefix of Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1961 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1961 in Java, C++, or Python.