From d219aa065c52940572911db2fd709035dc0b406c Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Mon, 2 Dec 2024 16:12:28 +0530 Subject: [PATCH] Create 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence --- ...curs As a Prefix of Any Word in a Sentence | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence diff --git a/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence b/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence new file mode 100644 index 0000000..221b185 --- /dev/null +++ b/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence @@ -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 + } +};