Member-only story

Leetcode 1455: Check If a Word Occurs As a Prefix of Any Word in a Sentence

Pierre-Marie Poitevin
1 min readMay 29, 2020

--

In this Leetcode problem, we are trying to find the index of the word with a given prefix.

Problem statement

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 :)

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet