array and hashmap
August 22, 2022
Check if a word occurs as a prefix of any word in a sentence
We will split the string with space then iterate over each word to check the prefix, if we find one, we return the position of the word in the sentence, else we return -1.
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
sentence = sentence.split(" ")
for i, word in enumerate(sentence):
if word.startswith(searchWord):
return i+1
return -1
Time Complexity: O(n)
Space Complexity: O(n)