Home Backend Development PHP Tutorial Sentence Similarity III

Sentence Similarity III

Oct 07, 2024 am 06:08 AM

Sentence Similarity III

1813. Sentence Similarity III

Difficulty: Medium

Topics: Array, Two Pointers, String

You are given two strings sentence1 and sentence2, each representing a sentence composed of words. A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of only uppercase and lowercase English characters.

Two sentences s1 and s2 are considered similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. Note that the inserted sentence must be separated from existing words by spaces.

For example,

  • s1 = "Hello Jane" and s2 = "Hello my name is Jane" can be made equal by inserting "my name is" between "Hello" and "Jane" in s1.
  • s1 = "Frog cool" and s2 = "Frogs are cool" are not similar, since although there is a sentence "s are" inserted into s1, it is not separated from "Frog" by a space.

Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false.

Example 1:

  • Input: sentence1 = "My name is Haley", sentence2 = "My Haley"
  • Output: true
  • Explanation: sentence2 can be turned to sentence1 by inserting "name is" between "My" and "Haley".

Example 2:

  • Input: sentence1 = "of", sentence2 = "A lot of words"
  • Output: false
  • Explanation: No single sentence can be inserted inside one of the sentences to make it equal to the other.

Example 3:

  • Input: sentence1 = "Eating right now", sentence2 = "Eating"
  • Output: true
  • Explanation: sentence2 can be turned to sentence1 by inserting "right now" at the end of the sentence.

Constraints:

  • 1 <= sentence1.length, sentence2.length <= 100
  • sentence1 and sentence2 consist of lowercase and uppercase English letters and spaces.
  • The words in sentence1 and sentence2 are separated by a single space.

Hint:

  1. One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence.
  2. Get the longest common prefix between them and the longest common suffix.

Solution:

We can approach it by comparing the longest common prefix and suffix of both sentences. If the words in the remaining part of one sentence are completely contained within the other sentence (possibly empty), then the sentences can be considered similar.

Steps:

  1. Split both sentences into arrays of words.
  2. Use two pointers to compare the longest common prefix from the start of both arrays.
  3. Use another two pointers to compare the longest common suffix from the end of both arrays.
  4. After comparing the common prefix and suffix, if the remaining words in one of the sentences form an empty array (meaning they have all been matched), then the sentences are considered similar.

Let's implement this solution in PHP: 1813. Sentence Similarity III


/**

  • @param String $sentence1
  • @param String $sentence2
  • @return Boolean / function areSentencesSimilar($sentence1, $sentence2) { ... ... ... /*
    • go to ./solution.php */ }

// Test examples
$sentence1 = "My name is Haley";
$sentence2 = "My Haley";
echo areSentencesSimilar($sentence1, $sentence2) ? 'true' : 'false'; // Output: true

$sentence1 = "of";
$sentence2 = "A lot of words";
echo areSentencesSimilar($sentence1, $sentence2) ? 'true' : 'false'; // Output: false

$sentence1 = "Eating right now";
$sentence2 = "Eating";
echo areSentencesSimilar($sentence1, $sentence2) ? 'true' : 'false'; // Output: true
?>




Explanation:

  1. Splitting sentences into words: We use explode() to split the sentence strings into arrays of words.
  2. Common prefix comparison: We iterate over both arrays from the start and compare corresponding words. The loop continues as long as the words match.
  3. Common suffix comparison: We compare the words from the end of both arrays, again using a loop to check for matching words.
  4. Final check: After processing the common prefix and suffix, we check if the number of words that have been matched (prefix suffix) covers all the words in the shorter sentence. If so, the sentences can be considered similar.

Time Complexity:

  • The time complexity is O(n m), where n and m are the lengths of sentence1 and sentence2 respectively. This is because we process the words in both sentences only once while checking the common prefix and suffix.

This solution should work efficiently given the constraints.

Contact Links

Wenn Sie diese Serie hilfreich fanden, denken Sie bitte darüber nach, dem Repository einen Stern auf GitHub zu geben oder den Beitrag in Ihren bevorzugten sozialen Netzwerken zu teilen? Ihre Unterstützung würde mir sehr viel bedeuten!

Wenn Sie weitere hilfreiche Inhalte wie diesen wünschen, folgen Sie mir gerne:

  • LinkedIn
  • GitHub

The above is the detailed content of Sentence Similarity III. 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 尊渡假赌尊渡假赌尊渡假赌

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-

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

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.

See all articles