-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathFirstUniqueCharacter.kt
37 lines (34 loc) · 1.17 KB
/
FirstUniqueCharacter.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
/**
* Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
* [Source](https://leetcode.com/problems/first-unique-character-kt/)
*/
@UseCommentAsDocumentation
fun firstUniqChar(s: String): Int {
val orderedMap = LinkedHashMap<Char, Int>() // char to its index map
val removedSet = mutableSetOf<Char>()
for (i in 0..s.lastIndex) {
val char = s[i]
if (removedSet.contains(char)) {
continue
}
val index = orderedMap[char]
if (index != null) {
// [char] is not unique
removedSet.add(char)
orderedMap.remove(char)
} else {
// [char] has not been seen before
orderedMap[char] = i
}
}
val firstKey = orderedMap.keys.firstOrNull() ?: return -1
return orderedMap[firstKey] ?: -1 // since [orderedMap] is well... ordered, the answer will be on first key
}
fun main() {
firstUniqChar(s = "loveleetcode") shouldBe 2
firstUniqChar(s = "leetcode") shouldBe 0
firstUniqChar(s = "aabb") shouldBe -1
}