Input: s ="iloveleetcode", words =["i","love","leetcode","apples"]Output: trueExplanation:
s can be made by concatenating "i","love", and "leetcode" together.
We want to check if the string s can be formed by concatenating the first k words from the array. This is a straightforward prefix check using two pointers: one for the string and one for the array.
By iterating through the words and matching their characters with the corresponding characters in s, we can verify if s is a prefix. If we reach the end of s exactly after some words, then s is a prefix of the array.
classSolution {
public:bool isPrefixString(string s, vector<string>& words) {
int i =0;
for (const string& w : words) {
for (char c : w) {
if (i == s.size() || s[i] != c) return false;
++i;
}
if (i == s.size()) return true;
}
return i == s.size();
}
};
classSolution {
publicbooleanisPrefixString(String s, String[] words) {
int i = 0;
for (String w : words) {
for (char c : w.toCharArray()) {
if (i == s.length() || s.charAt(i) != c) returnfalse;
i++;
}
if (i == s.length()) returntrue;
}
return i == s.length();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funisPrefixString(s: String, words: Array<String>): Boolean {
var i = 0for (w in words) {
for (c in w) {
if (i == s.length || s[i] != c) returnfalse i++ }
if (i == s.length) returntrue }
return i == s.length
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defis_prefix_string(self, s: str, words: list[str]) -> bool:
i =0for w in words:
for c in w:
if i == len(s) or s[i] != c:
returnFalse i +=1if i == len(s):
returnTruereturn i == len(s)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnis_prefix_string(s: String, words: Vec<String>) -> bool {
letmut i =0;
let s_bytes = s.as_bytes();
for w in words {
for&c in w.as_bytes() {
if i == s_bytes.len() || s_bytes[i] != c {
returnfalse;
}
i +=1;
}
if i == s_bytes.len() {
returntrue;
}
}
i == s_bytes.len()
}
}