-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1061_Lexicographically_Smallest_Equivalent_String.java
65 lines (47 loc) · 1.48 KB
/
1061_Lexicographically_Smallest_Equivalent_String.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* 1061. Lexicographically Smallest Equivalent String
* Problem Link: https://leetcode.com/problems/lexicographically-smallest-equivalent-string
* Difficulty: Medium
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
int[] parent = new int[26];
// returns the top most parent of x
private int find(int x) {
if (parent[x] == -1) {
return x;
}
return parent[x] = find(parent[x]);
}
private void union(int x, int y) {
// find the top most parent of x and y
// i.e., smallest value they will map to
x = find(x);
y = find(y);
if (x==y) return;
// now, if both are different, make parent[large]=small
if (x > y) {
parent[x] = y;
}
else {
parent[y] = x;
}
}
public String smallestEquivalentString(String s1, String s2, String baseStr) {
// parent will be smaller than child
Arrays.fill(parent, -1);
int n = s1.length();
for (int i = 0; i < n; i++ ) {
union(s1.charAt(i)-'a', s2.charAt(i)-'a');
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < baseStr.length(); i++) {
sb.append((char)(find(baseStr.charAt(i) - 'a') + 'a'));
}
return sb.toString();
}
}