Check If a Word Occurs As a Prefix of Any Word in a Sentence

The problem asks to return the index of the word in the sentence where the searchWord is a prefix of that word. If there are multiple such words, return the index of the first word. If there is no such word, return -1.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
        # Split the sentence into words
        words = sentence.split()

        # Iterate over the words with their indices
        for i, word in enumerate(words):
            # If a word starts with the searchWord, return the 1-indexed position
            if word.startswith(searchWord):
                return i + 1

        # If no word starts with the searchWord, return -1
        return -1

In this code, we first split the sentence into words. Then, we iterate over each word with its index. For each word, we check if it starts with the searchWord. If it does, we return the 1-indexed position of the word. If no word starts with the searchWord, we return -1.