Skip to content

1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence #903

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We can break down the task into the following steps:

  1. Split the sentence into individual words.
  2. Iterate through the words and check if the searchWord is a prefix of each word.
  3. If a word starts with searchWord, return the 1-indexed position of the word.
  4. If no word matches, return -1.

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 $i…

Replies: 1 comment 2 replies

Comment options

mah-shamim
Dec 2, 2024
Maintainer Author

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Dec 2, 2024
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants