Skip to content

Commit 704285e

Browse files
Merge pull request #2804 from sarthaksarangi/main
Update 0049-group-anagrams.java
2 parents 7fa2b21 + 47ccc16 commit 704285e

File tree

1 file changed

+13
-13
lines changed

1 file changed

+13
-13
lines changed

java/0049-group-anagrams.java

+13-13
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
11
class Solution {
2-
32
public List<List<String>> groupAnagrams(String[] strs) {
4-
List<List<String>> res = new ArrayList<>();
5-
if (strs.length == 0) return res;
6-
HashMap<String, List<String>> map = new HashMap<>();
7-
for (String s : strs) {
8-
int[] hash = new int[26];
9-
for (char c : s.toCharArray()) {
10-
hash[c - 'a']++;
3+
Map<String, List<String>> map = new HashMap<>();
4+
5+
for (String word : strs) {
6+
char[] chars = word.toCharArray();
7+
Arrays.sort(chars);
8+
String sortedWord = new String(chars);
9+
10+
if (!map.containsKey(sortedWord)) {
11+
map.put(sortedWord, new ArrayList<>());
1112
}
12-
String key = new String(Arrays.toString(hash));
13-
map.computeIfAbsent(key, k -> new ArrayList<>());
14-
map.get(key).add(s);
13+
14+
map.get(sortedWord).add(word);
1515
}
16-
res.addAll(map.values());
17-
return res;
16+
17+
return new ArrayList<>(map.values());
1818
}
1919
}

0 commit comments

Comments
 (0)