LeetCode 1061. Lexicographically Smallest Equivalent String
原题链接在这里:https://leetcode.com/problems/lexicographically-smallest-equivalent-string/
题目:
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:
A
B
[m,p]
[a,o]
[k,r,s]
[e,i]
"makkek"
Example 2:
A
B
[h,w]
[d,e,o]
[l,r]
'o'
S
'd'
"hdld"
Example 3:
A
B
[a,o,e,r,s,c]
[l,p]
[g,t]
[d,m]
S
'u'
'd'
'a'
"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 Map<Character, Character> parent = new HashMap<>(); 3 4 public String smallestEquivalentString(String A, String B, String S) { 5 for(int i = 0; i<A.length(); i++){ 6 char a = A.charAt(i); 7 char b = B.charAt(i); 8 9 if(find(a) != find(b)){ 10 union(a, b); 11 } 12 } 13 14 StringBuilder sb = new StringBuilder(); 15 for(int i = 0; i<S.length(); i++){ 16 char anc = find(S.charAt(i)); 17 sb.append(anc); 18 } 19 20 return sb.toString(); 21 } 22 23 private char find(char c){ 24 parent.putIfAbsent(c, c); 25 if(c != parent.get(c)){ 26 char anc = find(parent.get(c)); 27 parent.put(c, anc); 28 } 29 30 return parent.get(c); 31 } 32 33 private void union(char a, char b){ 34 char c1 = find(a); 35 char c2 = find(b); 36 if(c1 < c2){ 37 parent.put(c2, c1); 38 }else{ 39 parent.put(c1, c2); 40 } 41 } 42 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步