916. Word Subsets #1114
-
Topics: You are given two string arrays A string
A string Return an array of all the universal strings in Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to identify the words in Approach:
Let's implement this solution in PHP: 916. Word Subsets <?php
/**
* @param String[] $words1
* @param String[] $words2
* @return String[]
*/
function wordSubsets($words1, $words2) {
// Step 1: Build a frequency map for the maximum counts of characters in words2
$freqB = [];
foreach ($words2 as $word) {
$count = count_chars($word, 1); // get character counts for each word in words2
foreach ($count as $char => $c) {
$freqB[$char] = max(isset($freqB[$char]) ? $freqB[$char] : 0, $c);
}
}
// Step 2: Check each word in words1
$result = [];
foreach ($words1 as $word) {
$countA = count_chars($word, 1); // get character counts for the word in words1
$isValid = true;
// Step 3: Check if the word in words1 meets the required character frequencies
foreach ($freqB as $char => $freq) {
if (isset($countA[$char]) && $countA[$char] >= $freq) {
continue;
}
$isValid = false;
break;
}
// Step 4: If valid, add the word to the result
if ($isValid) {
$result[] = $word;
}
}
return $result;
}
// Example usage:
$words1 = ["amazon", "apple", "facebook", "google", "leetcode"];
$words2 = ["e", "o"];
print_r(wordSubsets($words1, $words2)); // Output: ["facebook", "google", "leetcode"]
$words2 = ["l", "e"];
print_r(wordSubsets($words1, $words2)); // Output: ["apple", "google", "leetcode"]
?> Explanation:
Time Complexity:
This approach ensures that we check each word efficiently and meets the problem's constraints. |
Beta Was this translation helpful? Give feedback.
We need to identify the words in
words1
that are "universal", meaning each string inwords2
is a subset of the word fromwords1
.Approach:
Count the Frequency of Characters in
words2
:words2
. This gives us the required number of occurrences for each character to be a subset.Check Each Word in
words1
:words1
, count the frequency of each character.words1
meet or exceed the required counts fromwords2
, then the word is universal.Return the Universal Words:
words1
, return the ones that are universal.Let's…