Skip to content

Commit a0c0755

Browse files
committed
Group Anagrams
1 parent 73a6d43 commit a0c0755

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

group-anagrams/TonyKim9401.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// TC: O(n)
2+
// SC: O(n * m)
3+
class Solution {
4+
public List<List<String>> groupAnagrams(String[] strs) {
5+
List<List<String>> output = new ArrayList<>();
6+
Map<String, List<String>> map = new HashMap<>();
7+
8+
for (int i = 0; i < strs.length; i++) {
9+
char[] charArray = strs[i].toCharArray();
10+
Arrays.sort(charArray);
11+
String target = new String(charArray);
12+
13+
if (map.containsKey(target)) {
14+
map.get(target).add(strs[i]);
15+
} else {
16+
List<String> inside = new ArrayList<>();
17+
inside.add(strs[i]);
18+
map.put(target, inside);
19+
}
20+
}
21+
22+
for (String key : map.keySet()) output.add(map.get(key));
23+
return output;
24+
}
25+
}

0 commit comments

Comments
 (0)