884. Uncommon Words from Two Sentences #560
Answered
by
basharul-siddike
mah-shamim
asked this question in
Q&A
-
Topics: A sentence is a string of single-space separated words where each word consists only of lowercase letters. A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence. Given two sentences Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Answered by
basharul-siddike
Sep 17, 2024
Replies: 1 comment 2 replies
-
We can follow these steps:
Approach:
Let's implement this solution in PHP: 884. Uncommon Words from Two Sentences <?php
/**
* @param String $s1
* @param String $s2
* @return String[]
*/
function uncommonFromSentences($s1, $s2) {
// Split the sentences into words
$words1 = explode(' ', $s1);
$words2 = explode(' ', $s2);
// Initialize an array to hold the frequency of each word
$wordCount = array();
// Count the occurrences of each word from both sentences
foreach ($words1 as $word) {
if (isset($wordCount[$word])) {
$wordCount[$word]++;
} else {
$wordCount[$word] = 1;
}
}
foreach ($words2 as $word) {
if (isset($wordCount[$word])) {
$wordCount[$word]++;
} else {
$wordCount[$word] = 1;
}
}
// Collect the uncommon words (words that appear only once)
$result = array();
foreach ($wordCount as $word => $count) {
if ($count == 1) {
$result[] = $word;
}
}
return $result;
}
// Test cases
$s1 = "this apple is sweet";
$s2 = "this apple is sour";
print_r(uncommonFromSentences($s1, $s2)); // Output: ["sweet", "sour"]
$s1 = "apple apple";
$s2 = "banana";
print_r(uncommonFromSentences($s1, $s2)); // Output: ["banana"]
?> Explanation:
Example Walkthrough:
Time Complexity:
Space Complexity:
|
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
mah-shamim
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We can follow these steps:
s1
ands2
into individual words.Approach:
explode
function to split the sentences into arrays of words.Let's implement this solution in PHP: 884. Uncommon Words from Two Sentences