Tech for good

[Leetcode/String Manipulation] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence 본문

IT/Computer Science

[Leetcode/String Manipulation] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence

Diana Kang 2025. 2. 18. 22:48

class Solution:
    def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
        words = sentence.split()
        for i, word in enumerate(words):
            if word.startwith(searchword):
                return i+1
        return -1

Explanation:

  1. Split the Sentence: The input sentence is split into a list of words using .split(), which automatically handles single spaces.
  2. Iterate Over Words: We loop through the words using enumerate(), which gives both the index (i) and the word.
  3. Check for Prefix: If a word starts with searchWord, we return its 1-based index (i + 1).
  4. Return -1 if Not Found: If no word matches the prefix condition, return -1.

Complexity Analysis:

  • Time Complexity: O(n) where nn is the number of words in the sentence, since we iterate through the words once.
  • Space Complexity: O(1) since we only store the words list temporarily.