1813. Sentence Similarity III #670
-
Topics: You are given two strings Two sentences For example,
Given two sentences Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
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:
Let's implement this solution in PHP: 1813. Sentence Similarity III <?php
/**
* @param String $sentence1
* @param String $sentence2
* @return Boolean
*/
function areSentencesSimilar($sentence1, $sentence2) {
// Split both sentences into arrays of words
$words1 = explode(" ", $sentence1);
$words2 = explode(" ", $sentence2);
$i = 0;
$j = 0;
$n1 = count($words1);
$n2 = count($words2);
// Compare the longest common prefix
while ($i < $n1 && $i < $n2 && $words1[$i] == $words2[$i]) {
$i++;
}
// Compare the longest common suffix
while ($j < $n1 - $i && $j < $n2 - $i && $words1[$n1 - 1 - $j] == $words2[$n2 - 1 - $j]) {
$j++;
}
// Check if the remaining unmatched parts form an empty array
return $i + $j >= min($n1, $n2);
}
// 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:
Time Complexity:
This solution should work efficiently given the constraints. |
Beta Was this translation helpful? Give feedback.
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:
Let's implement this …