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)
.
1using System;
2
3public class PrefixFinder {
4 public static int PrefixInSentence(string sentence, string searchWord) {
5 string[] words = sentence.Split(' ');
6 for (int i = 0; i < words.Length; i++) {
7 if (words[i].StartsWith(searchWord)) {
8 return i + 1;
9 }
10 }
11 return -1;
12 }
13
14 public static void Main() {
15 string sentence = "i love eating burger";
16 string searchWord = "burg";
17 Console.WriteLine(PrefixInSentence(sentence, searchWord));
18 }
19}
Splitting the sentence into words using Split
and iterating over them. If the word starts with the searchWord, the shifted index is returned.
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.
Operates with two pointers and skips over spaces efficiently while moving to next word with index increment. The inner loop handles prefix matching directly.