Check If String Is a Prefix of Array
We’ll iterate through the words array, and for each word, we’ll check if it is a prefix of the remaining part of the string s
. If we reach a point where the remaining part of s
becomes empty, then s
is indeed a prefix string of words.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| class Solution:
def isPrefixString(self, s: str, words: List[str]) -> bool:
# Iterate through the words array
for word in words:
# Check if the current word is a prefix of the remaining part of s
if s.startswith(word):
# If yes, remove the current word from the beginning of s
s = s[len(word):]
else:
# If no, then s cannot be made by concatenating a prefix of words
return False
# If the remaining part of s is empty, then s is a prefix string of words
if s == "":
return True
# If s is not empty after iterating through all words, then s is not a prefix string of words
return False
|
The code returns true
if s
can be made by concatenating a prefix of words
, and false
otherwise. It leverages the startswith
method to compare the prefixes efficiently.