LC: 1061. Lexicographically Smallest Equivalent String
https://leetcode.com/problems/lexicographically-smallest-equivalent-string/
You are given two strings of the same length s1 and s2 and a string baseStr.
We say s1[i] and s2[i] are equivalent characters.
For example, if
s1 = "abc"ands2 = "cde", then we have'a' == 'c','b' == 'd', and'c' == 'e'.
Equivalent characters follow the usual rules of any equivalence relation:
Reflexivity:
'a' == 'a'.Symmetry:
'a' == 'b'implies'b' == 'a'.Transitivity:
'a' == 'b'and'b' == 'c'implies'a' == 'c'.
For example, given the equivalency information from s1 = "abc" and s2 = "cde", "acd" and "aab" are equivalent strings of baseStr = "eed", and "aab" is the lexicographically smallest equivalent string of baseStr.
Return the lexicographically smallest equivalent string of baseStr by using the equivalency information from s1 and s2.
Example 1:
Input: s1 = "parker", s2 = "morris", baseStr = "parser"
Output: "makkek"
Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i].
The characters in each group are equivalent and sorted in lexicographical order.
So the answer is "makkek".Example 2:
Input: s1 = "hello", s2 = "world", baseStr = "hold"
Output: "hdld"
Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r].
So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld".Example 3:
Constraints:
1 <= s1.length, s2.length, baseStr <= 1000s1.length == s2.lengths1,s2, andbaseStrconsist of lowercase English letters.
The Essence:
Die “Äquivalenz-Beziehung” zwischen den Zeichen kann man als eine Beziehung zwischen den Knoten eines Graphs betrachten. Der Graph konstruieren wir mithilfe der Strings s1 und s2. Für jedes Zeichen baseStr finden wir das kleinste Zeichen, die von dem Knoten dieses Zeichens angefangen traversiert werden kann. Der Graph kann natürlich nicht zusammenhängend sein.
Details:
Für ein solches Problem bietet die Graphentheorie 3 Hauptlösungen. Diese sind nämlich Tiefensuche, Breitensuche und die Union-Find-Struktur, bei welcher der Wurzel jeder Menge das kleinste Zeichen ist.
Default Code:
Last updated