-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathGroupAnagrams.kt
76 lines (61 loc) · 1.84 KB
/
GroupAnagrams.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.daily.algothrim.leetcode.top150
/**
* 49. 字母异位词分组
*/
/*
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母
*/
class GroupAnagrams {
companion object {
@JvmStatic
fun main(args: Array<String>) {
GroupAnagrams().groupAnagrams(arrayOf("eat", "tea", "tan", "ate", "nat", "bat")).forEach {
it.forEach { item ->
print("$item, ")
}
println()
}
println()
GroupAnagrams().groupAnagrams(arrayOf("")).forEach {
it.forEach { item ->
print("$item, ")
}
println()
}
println()
GroupAnagrams().groupAnagrams(arrayOf("a")).forEach {
it.forEach { item ->
print("$item, ")
}
println()
}
println()
}
}
fun groupAnagrams(strs: Array<String>): List<List<String>> {
val map = hashMapOf<String, ArrayList<String>>()
for (item in strs) {
val c = item.toCharArray().apply { sort() }.concatToString()
map[c] = map.getOrDefault(c, arrayListOf()).apply { add(item) }
}
val result = arrayListOf<List<String>>()
for (item in map) {
result.add(item.value)
}
return result
}
}