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)
.
1#include <stdio.h>
2#include <string.h>
3
4int isPrefix(char *word, char *searchWord) {
5 return strncmp(word, searchWord, strlen(searchWord)) == 0;
6}
7
8int prefixInSentence(char *sentence, char *searchWord) {
9 int index = 1;
10 char *word = strtok(sentence, " ");
11 while (word != NULL) {
12 if (isPrefix(word, searchWord))
13 return index;
14 word = strtok(NULL, " ");
15 index++;
16 }
17 return -1;
18}
19
20int main() {
21 char sentence[] = "i love eating burger";
22 char searchWord[] = "burg";
23 int result = prefixInSentence(sentence, searchWord);
24 printf("%d\n", result);
25 return 0;
26}
Using strtok
to split the sentence into words. For each word, strncmp
checks if the searchWord
is a prefix. The index is returned if found; otherwise, it continues. If no prefix is found, -1
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.
A straightforward two-pointer style implementation where i
traverses the sentence and j
tries to match the search_word
. The pointer skips spaces smartly, and converges on a solution quickly.