Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e8b7248

Browse files
committed
Solve 1061. Lexicographically Smallest Equivalent String
1 parent 80f0456 commit e8b7248

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
3+
fun findRootIndex(equivalents: IntArray, c: Char): Int {
4+
var i = c.toInt() - 'a'.toInt()
5+
6+
while (i != equivalents[i]) {
7+
i = equivalents[i]
8+
}
9+
10+
return i
11+
}
12+
13+
fun smallestEquivalentString(s1: String, s2: String, baseStr: String): String {
14+
val equivalents = IntArray(26) { i -> i }
15+
16+
s1.zip(s2).forEach { (c1, c2) ->
17+
if (c1 != c2) {
18+
val i1 = findRootIndex(equivalents, c1)
19+
val i2 = findRootIndex(equivalents, c2)
20+
21+
when {
22+
i1 < i2 -> equivalents[i2] = i1
23+
else -> equivalents[i1] = i2
24+
}
25+
}
26+
}
27+
28+
return baseStr.map {
29+
('a'.toInt() + equivalents[findRootIndex(equivalents, it)]).toChar()
30+
}.joinToString("")
31+
}
32+
33+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /