Skip to content

Commit 46be45b

Browse files
authored
Create 1061-lexicographically-smallest-equivalent-string.js
1 parent 9a96c5d commit 46be45b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @param {string} s1
3+
* @param {string} s2
4+
* @param {string} baseStr
5+
* @return {string}
6+
*/
7+
var smallestEquivalentString = function (s1, s2, baseStr) {
8+
if (s1.length === 0 || s2.length === 0) return ''
9+
const uf = new UnionFind()
10+
for (let i = 0; i < s1.length; i++) {
11+
uf.union(s1[i], s2[i])
12+
}
13+
let res = ''
14+
for (const ch of baseStr) {
15+
res += uf.find(ch) || ch // some letters don't have connected component
16+
}
17+
return res
18+
}
19+
class UnionFind {
20+
constructor() {
21+
this.parents = new Map()
22+
}
23+
find(x) {
24+
if (this.parents.get(x) === x) return x
25+
this.parents.set(x, this.find(this.parents.get(x))) // path compression
26+
return this.parents.get(x)
27+
}
28+
union(u, v) {
29+
// init
30+
if (!this.parents.has(u)) {
31+
this.parents.set(u, u)
32+
}
33+
if (!this.parents.has(v)) {
34+
this.parents.set(v, v)
35+
}
36+
// find root
37+
const rootU = this.find(u)
38+
const rootV = this.find(v)
39+
if (rootU === rootV) return // connected already
40+
// set smallest lex as the root
41+
if (rootU > rootV) {
42+
this.parents.set(rootU, rootV)
43+
} else {
44+
this.parents.set(rootV, rootU)
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)