mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
problems: add „387. First Unique Character in a String“
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
dbb22b755d
commit
fa54cd1335
1 changed files with 26 additions and 0 deletions
26
problems/first-unique-character-in-a-string.kt
Normal file
26
problems/first-unique-character-in-a-string.kt
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
class Solution {
|
||||||
|
private data class Accumulator(val firstIndex: Int, var count: Int = 0) {
|
||||||
|
fun add() {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun firstUniqChar(s: String): Int = s
|
||||||
|
.foldIndexed(mutableMapOf<Char, Accumulator>()) { i, acc, c ->
|
||||||
|
acc.getOrPut(c) { Accumulator(i) }.add()
|
||||||
|
acc
|
||||||
|
}
|
||||||
|
.filterValues { it.count == 1 }
|
||||||
|
.minByOrNull { (_, acc) -> acc.firstIndex }
|
||||||
|
?.value
|
||||||
|
?.firstIndex
|
||||||
|
?: -1
|
||||||
|
}
|
||||||
|
|
||||||
|
fun main() {
|
||||||
|
val s = Solution()
|
||||||
|
|
||||||
|
check(s.firstUniqChar("leetcode") == 0)
|
||||||
|
check(s.firstUniqChar("loveleetcode") == 2)
|
||||||
|
check(s.firstUniqChar("aabb") == -1)
|
||||||
|
}
|
Loading…
Reference in a new issue