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.
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.