Friday, July 1, 2022
HomeWordPress DevelopmentLeetcode Options: Test If a Phrase Happens As a Prefix of Any...

Leetcode Options: Test If a Phrase Happens As a Prefix of Any Phrase in a Sentence


Given a sentence that consists of some phrases separated by a single house, and a searchWord, examine if searchWord is a prefix of any phrase in sentence.

Return the index of the phrase in sentence (1-indexed) the place searchWord is a prefix of this phrase. If searchWord is a prefix of a couple of phrase, return the index of the primary phrase (minimal index). If there is no such thing as a such phrase return -1.

A prefix of a string s is any main contiguous substring of s.

Right here is my answer:


class Answer(object):
    def isPrefixOfWord(self, sentence, searchWord):
        """
        :sort sentence: str
        :sort searchWord: str
        :rtype: int
        """

        s = sentence.cut up(" ")

        for i, phrase in enumerate(s):
            if phrase.startswith(searchWord):
                return i + 1


        return -1


Enter fullscreen mode

Exit fullscreen mode

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments