1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence #903
-
Topics: Given a Return the index of the word in A prefix of a string Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
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 <?php
/**
* @param String $sentence
* @param String $searchWord
* @return Integer
*/
function isPrefixOfWord($sentence, $searchWord) {
// Split the sentence into words
$words = explode(" ", $sentence);
// Iterate over the words to check if searchWord is a prefix
foreach ($words as $index => $word) {
// Check if searchWord is a prefix of the word
if (substr($word, 0, strlen($searchWord)) === $searchWord) {
// Return the 1-indexed position
return $index + 1;
}
}
// If no word contains searchWord as a prefix, return -1
return -1;
}
// Example Usage:
echo isPrefixOfWord("i love eating burger", "burg"); // Output: 4
echo isPrefixOfWord("this problem is an easy problem", "pro"); // Output: 2
echo isPrefixOfWord("i am tired", "you"); // Output: -1
?> Explanation:
Example Outputs:
Time Complexity:
This solution satisfies the constraints and is efficient for the given input size. |
Beta Was this translation helpful? Give feedback.
We can break down the task into the following steps:
sentence
into individual words.searchWord
is a prefix of each word.searchWord
, return the 1-indexed position of the word.-1
.Let's implement this solution in PHP: 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence