From fa54cd1335fc3bd2f488b1c3cc97bdb493807717 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 16 Aug 2022 11:10:52 +0200 Subject: [PATCH] =?UTF-8?q?problems:=20add=20=E2=80=9E387.=20First=20Uniqu?= =?UTF-8?q?e=20Character=20in=20a=20String=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- .../first-unique-character-in-a-string.kt | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 problems/first-unique-character-in-a-string.kt diff --git a/problems/first-unique-character-in-a-string.kt b/problems/first-unique-character-in-a-string.kt new file mode 100644 index 0000000..49a44bd --- /dev/null +++ b/problems/first-unique-character-in-a-string.kt @@ -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()) { 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) +}