Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution {
public:
int isPrefixOfWord(string sentence, string searchWord) {
int l = 0, r = 0, it = 0, ord = 0;
sentence += " "; // Append space to handle the last word
int length = searchWord.size();

while (r < sentence.size()) {
if (sentence[r] == ' ') { // If a space is found
ord++; // Increment word index
if (r - l >= length) { // Check if the word is long enough
while (l < r) { // Compare characters
if (searchWord[it] == sentence[l]) {
l++;
it++;
if (it == length) { // If all characters match
return ord; // Return the word index
}
} else { // Reset pointers for the next word
it = 0;
l = r + 1;
break;
}
}
} else {
l = r + 1; // Move to the next word
}
}
r++; // Increment right pointer
}

return -1; // Return -1 if no match is found
}
};
Loading