Skip to content

Commit 7441e9b

Browse files
author
Jeongwon Na
committed
group anagrams solution
1 parent 62952cb commit 7441e9b

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

group-anagrams/njngwn.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time Complexity: O(n), n: strs.length
2+
// Space Complexity: O(m+n), m: strMap.size, n: anagramList.size
3+
class Solution {
4+
public List<List<String>> groupAnagrams(String[] strs) {
5+
HashMap<String, ArrayList<String>> strMap = new HashMap<String, ArrayList<String>>();
6+
7+
for (String str : strs) {
8+
char[] charArr = str.toCharArray();
9+
Arrays.sort(charArr);
10+
String key = String.valueOf(charArr);
11+
12+
if (strMap.containsKey(key)) {
13+
strMap.get(key).add(str);
14+
} else {
15+
strMap.put(key, new ArrayList<String>(Arrays.asList(str)));
16+
}
17+
}
18+
19+
return new ArrayList<>(strMap.values());
20+
}
21+
}

0 commit comments

Comments
 (0)