-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path791-CustomSortString.kt
44 lines (36 loc) · 1.09 KB
/
791-CustomSortString.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
38
39
40
41
42
43
44
/**
* 791. Custom Sort String
* https://leetcode.com/problems/custom-sort-string/
*
*/
import java.util.*
class Solution {
fun customSortString(S: String, T: String): String {
val charOcurrence = buildCharOcurrenceMap(S)
var remainingString = ""
T.forEach {
if (!charOcurrence.contains(it)) {
remainingString += it
} else {
charOcurrence[it] = charOcurrence[it]!! + 1
}
}
return filterNonOcurringCharacters(S, charOcurrence) + remainingString
}
fun buildCharOcurrenceMap(s: String): LinkedHashMap<Char, Int> {
val charMap = LinkedHashMap<Char, Int>()
s.forEach {
charMap.put(it, 0)
}
return charMap
}
fun filterNonOcurringCharacters(s: String, ocurrences: Map<Char, Int>): String {
var filtered = ""
ocurrences.forEach { key, value ->
for (count in 0 until value) {
filtered += key
}
}
return filtered
}
}