Sponsored
Sponsored
This method involves splitting the input sentence into words and then iterating through each word to check if the searchWord is a prefix of that word. If a match is found, the index of the word (1-based) is returned. If no match is found, -1 is returned.
Time Complexity: O(n * m)
where n
is the number of words and m
is the average length of words.
Space Complexity: O(1)
.
1function prefixInSentence(sentence, searchWord) {
2 const words = sentence.split(' ');
3 for (let i = 0; i < words.length; i++) {
4 if (words[i].startsWith(searchWord)) {
5 return i + 1;
6 }
7 }
8 return -1;
9}
10
11// Example usage
12const sentence = "i love eating burger";
13const searchWord = "burg";
14console.log(prefixInSentence(sentence, searchWord));
Using split
method to tokenize the sentence. startsWith
checks if the searchWord
is a prefix. Returns a 1-based index if found.
This approach uses a two-pointer technique to traverse the sentence and words simultaneously for efficient prefix checking. It doesn't rely on splitting the string into words but rather navigates the sentence using custom logic.
Time Complexity: O(n)
where n
is the length of the sentence, as it efficiently traverses the string.
Space Complexity: O(1)
as only pointers are used.
public class PrefixFinderTwoPointer {
public static int PrefixInSentence(string sentence, string searchWord) {
int index = 1;
int i = 0;
while (i < sentence.Length) {
if (sentence[i] == ' ') {
i++;
continue;
}
int j = 0;
int start = i;
while (i < sentence.Length && sentence[i] != ' ' && j < searchWord.Length && sentence[i] == searchWord[j]) {
i++;
j++;
}
if (j == searchWord.Length) return index;
while (i < sentence.Length && sentence[i] != ' ') i++;
index++;
i++; // Move to next word
}
return -1;
}
public static void Main() {
Console.WriteLine(PrefixInSentence("i love eating burger", "burg"));
}
}
This solution employs two pointers and actively skips over spaces while counting index positions. It examines each character directly using the pointers for efficiency.