原题链接在这里:
题目:
Given strings A
and B
of the same length, we say A[i] and B[i] are equivalent characters. For example, if A = "abc"
and B = "cde"
, then we have 'a' == 'c', 'b' == 'd', '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 A
and B
above, S = "eed"
, "acd"
, and "aab"
are equivalent strings, and "aab"
is the lexicographically smallest equivalent string of S
.
Return the lexicographically smallest equivalent string of S
by using the equivalency information from A
and B
.
Example 1:
Input: A = "parker", B = "morris", S = "parser"Output: "makkek"Explanation: Based on the equivalency information in A and B, 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: A = "hello", B = "world", S = "hold"Output: "hdld"Explanation: Based on the equivalency information in A and B, we can group their characters as [h,w], [d,e,o], [l,r]. So only the second letter 'o' in S is changed to 'd', the answer is "hdld".
Example 3:
Input: A = "leetcode", B = "programs", S = "sourcecode"Output: "aauaaaaada"Explanation: We group the equivalent characters in A and B as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in S except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada".
Note:
- String
A
,B
andS
consist of only lowercase English letters from'a'
-'z'
. - The lengths of string
A
,B
andS
are between1
and1000
. - String
A
andB
are of the same length.
题解:
A and B are equal, for each index, the corresponding character in A and B should be in the same union.
When do the union, union by rank. a<c, a is c's parent.
Later, for each character of S, find its ancestor and append it to result.
Time Complexity: O((m+n)logm). m = A.length(), n = S.length(). find takes O(logm).
With path compression and union by rank, amatorize O(1).
Space: O(m).
AC Java:
1 class Solution { 2 Mapparent = new HashMap<>(); 3 4 public String smallestEquivalentString(String A, String B, String S) { 5 for(int i = 0; i