Given a sentence that consists of some words separated by a single space, and a searchWord.
You have to check if searchWord is a prefix of any word in sentence.
Return the index of the word in the sentence where searchWord is the prefix of this word.
If search word is the prefix of more than word, return the index of first word. If there is no such word return -1.
Ex:-
Input: sentence= "I love burger"
searchWord = "burg"
Output: 2
Ex:-
Input: sentence= "I am tired"
searchWord = "you"
Output: -1
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class MyClass { public static void main(String args[]) { String sentence = "this problem is an easy problem"; String searchWord = "pro"; System.out.println(findIndex(sentence, searchWord)); } public static int findIndex(String sentence, String searchWord){ String[] arr = sentence.split(" "); int len = searchWord.length(); for(int i=0; i<arr.length; i++){ if(arr[i].length() >= len){ if(arr[i].substring(0,len).equals(searchWord)) return i; } } return -1; } } |
Python
def findIndex(sentence, searchWord): arr = sentence.split(" ") l = len(searchWord) for i in range(0,len(arr)): if len(arr[i]) >= l: if arr[i][:l] == searchWord: return i return -1 sentence = "this problem is an easy problem" searchWord = "pro" print(findIndex(sentence, searchWord))