1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence
Difficulty: Easy
Topics: Two Pointers, String, String Matching
Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence.
Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.
A prefix of a string s is any leading contiguous substring of s.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
We can break down the task into the following steps:
Let's implement this solution in PHP: 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence
Explanation:
Splitting the Sentence into Words:
We use explode(" ", $sentence) to split the sentence into an array of words.Iterating Over Words:
Use a foreach loop to iterate through each word in the sentence. The $index variable keeps track of the position of the word (0-indexed).Checking for Prefix:
Use strpos($word, $searchWord) === 0 to check if the searchWord occurs at the start of the current word.Returning the Result:
If a match is found, return the 1-based index of the word by adding 1 to $index. If no match is found after the loop, return -1.Example Outputs:
This solution satisfies the constraints and is efficient for the given input size.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Check If a Word Occurs As a Prefix of Any Word in a Sentence. For more information, please follow other related articles on the PHP Chinese website!