Skip to content

Commit 52d7717

Browse files
authored
Create check-if-string-is-a-prefix-of-array.cpp
1 parent d1f7d6c commit 52d7717

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
bool isPrefixString(string s, vector<string>& words) {
7+
int i = 0, j = 0;
8+
for (const auto& c : s) {
9+
if (i == size(words) || words[i][j] != c) {
10+
return false;
11+
}
12+
if (++j == size(words[i])) {
13+
++i;
14+
j = 0;
15+
}
16+
}
17+
return j == 0;
18+
}
19+
};
20+
21+
// Time: O(n)
22+
// Space: O(1)
23+
class Solution2 {
24+
public:
25+
bool isPrefixString(string s, vector<string>& words) {
26+
int i = 0;
27+
for (const auto& word : words) {
28+
for (const auto& c : word) {
29+
if (i == size(s) || s[i] != c) {
30+
return false;
31+
}
32+
++i;
33+
}
34+
if (i == size(s)) {
35+
return true;
36+
}
37+
}
38+
return false;
39+
}
40+
};

0 commit comments

Comments
 (0)