Closed mah-shamim closed 1 week ago
We can follow these steps:
s1
and s2
into individual words.explode
function to split the sentences into arrays of words.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"]
?>
explode(' ', $s1)
and explode(' ', $s2)
to split the sentences into arrays of words.$wordCount
.$wordCount
array and add them to the result array.s1 = "this apple is sweet"
and s2 = "this apple is sour"
, after counting, the associative array $wordCount
will look like:
Array (
[this] => 2
[apple] => 2
[is] => 2
[sweet] => 1
[sour] => 1
)
The words with a count of 1 are sweet
and sour
, so the result is ["sweet", "sour"]
.
n
is the number of words in s1
and m
is the number of words in s2
. This is because we iterate through all the words in both sentences once to count the occurrences.n
and m
are the number of words in s1
and s2
. We store all the words in an associative array to track their counts.
Discussed in https://github.com/mah-shamim/leet-code-in-php/discussions/560
1 <= s1.length, s2.length <= 200
- `s1` and `s2` consist of lowercase English letters and spaces. - `s1` and `s2` do not have leading or trailing spaces. - All the words in `s1` and `s2` are separated by a single space.