Home Backend Development PHP Tutorial Check If a Word Occurs As a Prefix of Any Word in a Sentence

Check If a Word Occurs As a Prefix of Any Word in a Sentence

Dec 17, 2024 am 01:35 AM

Check If a Word Occurs As a Prefix of Any Word in a Sentence

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:

  • Input: sentence = "i love eating burger", searchWord = "burg"
  • Output: 4
  • Explanation: "burg" is prefix of "burger" which is the 4th word in the sentence.

Example 2:

  • Input: sentence = "this problem is an easy problem", searchWord = "pro"
  • Output: 2
  • Explanation: "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.

Example 3:

  • Input: sentence = "i am tired", searchWord = "you"
  • Output: -1
  • Explanation: "you" is not a prefix of any word in the sentence.

Constraints:

  • 1 <= sentence.length <= 100
  • 1 <= searchWord.length <= 10
  • sentence consists of lowercase English letters and spaces.
  • searchWord consists of lowercase English letters.

Hint:

  1. First extract the words of the sentence.
  2. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed)
  3. If searchWord doesn't exist as a prefix of any word return the default value (-1).

Solution:

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






Explanation:

  1. Splitting the Sentence into Words:

    We use explode(" ", $sentence) to split the sentence into an array of words.

  2. 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).

  3. Checking for Prefix:

    Use strpos($word, $searchWord) === 0 to check if the searchWord occurs at the start of the current word.

  4. 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:

  • For the input sentence = "i love eating burger" and searchWord = "burg", the output is 4 because "burger" is the 4th word.
  • For the input sentence = "this problem is an easy problem" and searchWord = "pro", the output is 2 because "problem" is the 2nd word.
  • For the input sentence = "i am tired" and searchWord = "you", the output is -1 because no word starts with "you".

Time Complexity:

  • Splitting the sentence into words takes O(n), where n is the length of the sentence.
  • Checking each word for a prefix takes O(m), where m is the length of the searchWord.
  • Thus, the overall time complexity is O(n * m), which is efficient for the input size constraints.

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:

  • LinkedIn
  • GitHub

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles