2901. Longest Unequal Adjacent Groups Subsequence II #1691
-
Topics: You are given a string array The hamming distance between two strings of equal length is the number of positions at which the corresponding characters are different. You need to select the longest subsequence1 from an array of indices
Return a string array containing the words corresponding to the indices (in order) in the selected subsequence. If there are multiple answers, return any of them. Note: strings in Example 1:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the longest subsequence of indices from given arrays Approach
Let's implement this solution in PHP: 2901. Longest Unequal Adjacent Groups Subsequence II <?php
/**
* @param String[] $words
* @param Integer[] $groups
* @return String[]
*/
function getWordsInLongestSubsequence($words, $groups) {
$n = count($words);
$dp = array_fill(0, $n, 1);
$prev = array_fill(0, $n, -1);
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $i; $j++) {
if ($groups[$i] == $groups[$j]) {
continue;
}
if (strlen($words[$i]) !== strlen($words[$j])) {
continue;
}
$diff = 0;
$len = strlen($words[$i]);
for ($k = 0; $k < $len; $k++) {
if ($words[$i][$k] != $words[$j][$k]) {
$diff++;
if ($diff > 1) {
break;
}
}
}
if ($diff == 1 && $dp[$j] + 1 > $dp[$i]) {
$dp[$i] = $dp[$j] + 1;
$prev[$i] = $j;
}
}
}
$max_len = max($dp);
$current_index = -1;
for ($i = $n - 1; $i >= 0; $i--) {
if ($dp[$i] == $max_len) {
$current_index = $i;
break;
}
}
$result = array();
while ($current_index != -1) {
array_unshift($result, $words[$current_index]);
$current_index = $prev[$current_index];
}
return $result;
}
// Example usage:
$words1 = array("bab", "dab", "cab");
$groups1 = array(1, 2, 2);
print_r(getWordsInLongestSubsequence($words1, $groups1)); // Possible output: ["bab", "cab"] or ["bab", "dab"]
$words2 = array("a", "b", "c", "d");
$groups2 = array(1, 2, 3, 4);
print_r(getWordsInLongestSubsequence($words2, $groups2)); // Output: ["a", "b", "c", "d"]
?> Explanation:
This approach efficiently computes the longest valid subsequence using dynamic programming and ensures correctness by adhering to the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the longest subsequence of indices from given arrays
words
andgroups
such that adjacent elements in the subsequence have different groups and their corresponding words have a Hamming distance of 1. The solution involves dynamic programming to track the longest valid subsequence ending at each index and backtracking to reconstruct the subsequence.Approach
dp[i]
represents the length of the longest valid subsequence ending at indexi
. Initialize each element ofdp
to 1 since each element by itself is a valid subsequence of length 1.prev
array to track the previous index in the subsequ…