Skip to content

Latest commit

 

History

History
59 lines (42 loc) · 1.6 KB

_1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence.md

File metadata and controls

59 lines (42 loc) · 1.6 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 01, 2024

Last updated : July 01, 2024


Related Topics : Two Pointers, String, String Matching

Acceptance Rate : 68.93 %


Solutions

Python

# Bit less efficient but thought it would be fun to code it this way

class Solution:
    def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
        wordStart = 0
        counter = 1

        while True :
            if sentence[wordStart:wordStart + len(searchWord)] == searchWord :
                return counter

            counter += 1
            wordStart = sentence.find(' ', wordStart) + 1
            
            if not wordStart :
                break

        return -1
class Solution:
    def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
        words = sentence.split(' ')
        for i in range(len(words)) :
            if words[i][:len(searchWord)] == searchWord :
                return i + 1

        return -1