1061. Lexicographically Smallest Equivalent String #1770
-
Topics: You are given two strings of the same We say
Equivalent characters follow the usual rules of any equivalence relation:
For example, given the equivalency information from Return the lexicographically smallest equivalent string of Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the lexicographically smallest equivalent string of Approach
Let's implement this solution in PHP: 1061. Lexicographically Smallest Equivalent String <?php
/**
* @param String $s1
* @param String $s2
* @param String $baseStr
* @return String
*/
function smallestEquivalentString($s1, $s2, $baseStr) {
$parent = range(0, 25);
$len = strlen($s1);
for ($i = 0; $i < $len; $i++) {
$a = $s1[$i];
$b = $s2[$i];
$idxA = ord($a) - ord('a');
$idxB = ord($b) - ord('a');
union($idxA, $idxB, $parent);
}
$res = '';
$lenBase = strlen($baseStr);
for ($i = 0; $i < $lenBase; $i++) {
$c = $baseStr[$i];
$idx = ord($c) - ord('a');
$root = find($idx, $parent);
$res .= chr($root + ord('a'));
}
return $res;
}
/**
* @param $x
* @param $parent
* @return mixed
*/
function find($x, &$parent) {
$r = $x;
while ($parent[$r] != $r) {
$r = $parent[$r];
}
$cur = $x;
while ($cur != $r) {
$next = $parent[$cur];
$parent[$cur] = $r;
$cur = $next;
}
return $r;
}
/**
* @param $x
* @param $y
* @param $parent
* @return void
*/
function union($x, $y, &$parent) {
$rootX = find($x, $parent);
$rootY = find($y, $parent);
if ($rootX == $rootY) {
return;
}
if ($rootX < $rootY) {
$parent[$rootY] = $rootX;
} else {
$parent[$rootX] = $rootY;
}
}
// Example usage
echo smallestEquivalentString("parker", "morris", "parser") . "\n"; // Output: "makkek"
echo smallestEquivalentString("hello", "world", "hold") . "\n"; // Output: "hdld"
echo smallestEquivalentString("leetcode", "programs", "sourcecode") . "\n"; // Output: "aauaaaaada"
?> Explanation:
This approach efficiently groups equivalent characters and ensures the smallest lexicographical representation by leveraging the Union-Find data structure with path compression and union by size (implicitly by smallest root). The complexity is nearly linear due to path compression, making it optimal for the given constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the lexicographically smallest equivalent string of
baseStr
by leveraging the equivalence information provided bys1
ands2
. The equivalence between characters follows the properties of reflexivity, symmetry, and transitivity. The solution involves grouping equivalent characters into connected components and representing each component with the smallest lexicographical character.Approach