Member-only story
Leetcode 1455: Check If a Word Occurs As a Prefix of Any Word in a Sentence
1 min readMay 29, 2020
In this Leetcode problem, we are trying to find the index of the word with a given prefix.
Solution
Simply go through the words and return the first one found
class Solution {
public int isPrefixOfWord(String sentence, String searchWord) {
String[] words = sentence.split(" ");
int n = words.length;
for (int i = 0; i < n; i++) {
String word = words[i];
if (word.startsWith(searchWord)) {
return i + 1;
}
}
return -1;
}
}
Happy coding :)