Similar Problems
Similar Problems not available
Check If A Word Occurs As A Prefix Of Any Word In A Sentence - Leetcode Solution
Companies:
LeetCode: Check If A Word Occurs As A Prefix Of Any Word In A Sentence Leetcode Solution
Difficulty: Easy
Topics: string two-pointers
Problem Statement:
Given a sentence and a string s, return true if s is a prefix of any word in the sentence.
A prefix of a string s is any leading contiguous substring of s.
Example:
Input: sentence = "i love eating burger", searchWord = "burg" Output: 4 Explanation: "burg" is prefix of "burger" which is the 4th word in the sentence.
Solution:
One way to solve this problem is to split the sentence into words and check if s is a prefix of any word. If a prefix is found, we return the index of the word in the sentence.
Here's the step by step guide to solve this problem in Python:
- Split the sentence into words using the "split()" function:
sentence = sentence.split()
- Use a for loop to iterate through each word in the sentence:
for i, word in enumerate(sentence):
- Check if the word starts with the given searchWord:
if word.startswith(searchWord):
- If the word starts with the searchWord, return the index of the word in the sentence:
return i+1 # index of the word in the sentence starts from 1
- If no prefix is found, return -1 to indicate that the searchWord is not a prefix of any word in the sentence:
return -1
Here's the full Python code to solve this problem:
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 # index of the word in the sentence starts from 1 return -1
Time Complexity:
The time complexity of this solution is O(n*m), where n is the number of words in the sentence and m is the length of the searchWord. This is because we need to iterate through each word in the sentence and check if it starts with the searchWord.
Space Complexity:
The space complexity of this solution is O(n), where n is the number of words in the sentence. This is because we are storing the sentence as a list of words.
Check If A Word Occurs As A Prefix Of Any Word In A Sentence Solution Code
1