|
1 | 1 | class Solution {
|
2 | | - public String smallestEquivalentString(String s1, String s2, String baseStr) { |
3 | | - int[] graph = new int[26]; |
4 | | - for (int i = 0; i < 26; i++) { |
5 | | - graph[i] = i; |
| 2 | + public String smallestEquivalentString(String s1, String s2, String baseStr) { |
| 3 | + UnionFind unionFind = new UnionFind(26); |
| 4 | + for (int i = 0; i < s1.length(); i++) { |
| 5 | + char c1 = s1.charAt(i); |
| 6 | + char c2 = s2.charAt(i); |
| 7 | + unionFind.union(c1 - 'a', c2 - 'a'); |
| 8 | + } |
| 9 | + StringBuilder result = new StringBuilder(); |
| 10 | + for (char c : baseStr.toCharArray()) { |
| 11 | + result.append((char) (unionFind.find(c - 'a') + 'a')); |
| 12 | + } |
| 13 | + return result.toString(); |
6 | 14 | }
|
7 | | - for (int i = 0; i < s1.length(); i++) { |
8 | | - int idxOne = s1.charAt(i) - 'a'; |
9 | | - int idxTwo = s2.charAt(i) - 'a'; |
10 | | - int parentOne = find(graph, idxOne); |
11 | | - int parentTwo = find(graph, idxTwo); |
12 | | - if(parentOne < parentTwo) { |
13 | | - graph[parentTwo] = parentOne; |
14 | | - } else { |
15 | | - graph[parentOne] = parentTwo; |
16 | | - } |
| 15 | + |
| 16 | + class UnionFind { |
| 17 | + private int[] parent; |
| 18 | + |
| 19 | + public UnionFind(int n) { |
| 20 | + parent = new int[n]; |
| 21 | + for (int i = 0; i < n; i++) { |
| 22 | + parent[i] = i; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + public int find(int node) { |
| 27 | + if (parent[node] == node) { |
| 28 | + return node; |
| 29 | + } |
| 30 | + parent[node] = find(parent[node]); |
| 31 | + return parent[node]; |
| 32 | + } |
| 33 | + |
| 34 | + public void union(int nodeOne, int nodeTwo) { |
| 35 | + int parentOne = find(nodeOne); |
| 36 | + int parentTwo = find(nodeTwo); |
| 37 | + if (parentOne != parentTwo) { |
| 38 | + if (parentOne < parentTwo) { |
| 39 | + parent[parentTwo] = parentOne; |
| 40 | + } else { |
| 41 | + parent[parentOne] = parentTwo; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
17 | 45 | }
|
18 | | - StringBuilder sb = new StringBuilder(); |
19 | | - for (char c : baseStr.toCharArray()) { |
20 | | - sb.append((char) ('a' + find(graph, c - 'a'))); |
21 | | - } |
22 | | - return sb.toString(); |
23 | | - } |
24 | | - |
25 | | - private int find(int[] graph, int idx) { |
26 | | - while(graph[idx] != idx) { |
27 | | - idx = graph[idx]; |
28 | | - } |
29 | | - return idx; |
30 | | - } |
31 | 46 | }
|
0 commit comments