File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
var smallestEquivalentString = function(A, B, S) {
2+
const set = new DisjointSet()
3+
4+
for (let i = 0; i < A.length; i++) {
5+
const aPos = posForChar(A[i])
6+
const bPos = posForChar(B[i])
7+
set.union(aPos, bPos)
8+
}
9+
10+
const result = []
11+
for (const char of S) {
12+
const sPos = posForChar(char)
13+
const parent = set.find(sPos)
14+
result.push(charForPos(parent))
15+
}
16+
17+
return result.join('')
18+
};
19+
20+
class DisjointSet {
21+
constructor() {
22+
this.parent = []
23+
for (let i = 0; i < 26; i++)
24+
this.parent[i] = i
25+
}
26+
27+
find(p) {
28+
let root = p
29+
while (root !== this.parent[root])
30+
root = this.parent[root]
31+
32+
while (p !== root) {
33+
const next = this.parent[p]
34+
this.parent[p] = root
35+
p = next
36+
}
37+
38+
return root
39+
}
40+
41+
union(p, q) {
42+
const rootP = this.find(p)
43+
const rootQ = this.find(q)
44+
45+
if (rootP === rootQ) return
46+
47+
if (rootP > rootQ) {
48+
this.parent[rootP] = rootQ
49+
} else {
50+
this.parent[rootQ] = rootP
51+
}
52+
}
53+
}
54+
55+
const posForChar = char => char.charCodeAt(0) - 'a'.charCodeAt(0)
56+
const charForPos = pos => String.fromCharCode(pos + 'a'.charCodeAt(0))

0 commit comments

Comments
 (0)