Q - Given a sentence
that consists of some words separated by a single space, and a searchWord
, check if searchWord
is a prefix of any word in sentence
.
Return the index of the word in sentence
(1-indexed) where searchWord
is a prefix of this word. If searchWord
is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1
.
A prefix of a string s
is any leading contiguous substring of s
.
LeetCode Problem: Link | Click Here
class Solution {
public int isPrefixOfWord(String sentence, String searchWord) {
// Split the sentence into separate words
String[] sentenceArray = sentence.split(" ");
int sentenceLen = sentenceArray.length;
int index = 0;
// Go through each word in the sentence
for (int i = 0; i < sentenceLen; i++) {
// Check if the current word begins with the searchWord
if (sentenceArray[i].startsWith(searchWord)) {
// If it does, note down its position (adding 1 to match human counting)
index = i + 1;
break; // Stop looking, we found a match
}
}
// If no match was found, return -1
if (index == 0) {
return -1;
} else {
// Otherwise, return the position of the word that starts with the searchWord
return index;
}
}
}