/ Data Structure and Algorithms  

Leetcode 49. Group Anagrams

Question



Given multiple strings, categorize them. As long as the strings contain exactly the same characters, they are counted as the same class, regardless of order.

Similar Questions

Solution

We can sort each string alphabetically, then we can map eat, tea, ate to aet. Others are similar.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
HashMap<String, List<String>> map = new HashMap<>();

// loop all strings
for (String str : strs) {
char[] charArray = str.toCharArray();

// sort
Arrays.sort(charArray);

String key = new String(charArray);

if (map.containsKey(key)) {
map.get(key).add(str);
} else {
List<String> tempList = new ArrayList<>();
tempList.add(str);

map.put(key, tempList);
}
}

return new ArrayList<>(map.values());