Skip to content
thesarfo

Reference

Check if a Word Occurs as a Prefix in a Sentence

Finding the first word in a sentence that has a given search word as its prefix.

views 0

Given a sentence and a searchWord, find the first word in the sentence that starts with searchWord as a prefix. (LeetCode 1455, LeetCode 2255, LeetCode 2185)

A prefix of a string is any leading part of it — for "burger", that’s "bur", "burg", or even "burger" itself. The sentence is just words separated by single spaces, so split it into a list and check each word.

Edge cases: if searchWord is longer than any word in the sentence, no word can start with it, so return -1 immediately; likewise if no word matches at all.

Approach

  1. Split the sentence into words.
  2. Iterate through each word, checking if it starts with searchWord via startsWith().
  3. Return the 1-indexed position of the first match.
  4. If no match is found, return -1.
class Solution {
public int isPrefixOfWord(String sentence, String searchWord) {
String[] words = sentence.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i].startsWith(searchWord)) {
return i + 1; // 1-indexed
}
}
return -1;
}
}