-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem49.kt
50 lines (40 loc) · 1.32 KB
/
Problem49.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
45
46
47
48
49
50
import Utils.*
// https://leetcode.com/problems/group-anagrams/description/
fun groupAnagrams(strs: Array<String>): List<List<String>> {
val groups = mutableMapOf<String, MutableList<String>>()
for (str in strs) {
val sorted = str.toCharArray().sorted().joinToString("")
if (groups.containsKey(sorted)) {
groups[sorted]!!.add(str)
} else {
groups[sorted] = mutableListOf(str)
}
}
return groups.values.toList()
}
fun test49() {
println("49) Group Anagrams:")
val ts =
mapOf(
arrayOf("eat", "tea", "tan", "ate", "nat", "bat") to listOf(listOf("bat"), listOf("nat", "tan"), listOf("ate", "eat", "tea")),
arrayOf("") to listOf(listOf("")),
arrayOf("a") to listOf(listOf("a")),
)
for ((input, expected) in ts) {
val actual = groupAnagrams(input)
val res = compare(expected, actual)
println("For ${input.contentToString()}: ${colorResult(res)}")
}
}
private fun compare(
l1: List<List<String>>,
l2: List<List<String>>,
): Boolean {
if (l1.size != l2.size) return false
val s1 = l1.sortedBy { it.size }
val s2 = l2.sortedBy { it.size }
for (i in s1.indices) {
if (s1[i].size != s2[i].size || !s1[i].containsAll(s2[i])) return false
}
return true
}