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)
.
1public class PrefixFinder {
2 public static int prefixInSentence(String sentence, String searchWord) {
3 String[] words = sentence.split(" ");
4 for (int i = 0; i < words.length; i++) {
5 if (words[i].startsWith(searchWord)) {
6 return i + 1;
7 }
8 }
9 return -1;
10 }
11
12 public static void main(String[] args) {
13 String sentence = "i love eating burger";
14 String searchWord = "burg";
15 System.out.println(prefixInSentence(sentence, searchWord));
16 }
17}
The split
method is used to tokenize the sentence into words. The startsWith
method checks if a word starts with the searchWord
. If so, the index (shifted for 1-based) 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.