Skip to content

Commit e9d3dd2

Browse files
authored
Create 1455. Check If a Word Occurs As a Prefix of Any Word in a Sent… (#649)
2 parents 4c1730e + d219aa0 commit e9d3dd2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public:
3+
int isPrefixOfWord(string sentence, string searchWord) {
4+
int l = 0, r = 0, it = 0, ord = 0;
5+
sentence += " "; // Append space to handle the last word
6+
int length = searchWord.size();
7+
8+
while (r < sentence.size()) {
9+
if (sentence[r] == ' ') { // If a space is found
10+
ord++; // Increment word index
11+
if (r - l >= length) { // Check if the word is long enough
12+
while (l < r) { // Compare characters
13+
if (searchWord[it] == sentence[l]) {
14+
l++;
15+
it++;
16+
if (it == length) { // If all characters match
17+
return ord; // Return the word index
18+
}
19+
} else { // Reset pointers for the next word
20+
it = 0;
21+
l = r + 1;
22+
break;
23+
}
24+
}
25+
} else {
26+
l = r + 1; // Move to the next word
27+
}
28+
}
29+
r++; // Increment right pointer
30+
}
31+
32+
return -1; // Return -1 if no match is found
33+
}
34+
};

0 commit comments

Comments
 (0)