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
- Split the sentence into words.
- Iterate through each word, checking if it starts with
searchWordviastartsWith(). - Return the 1-indexed position of the first match.
- 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; }}