-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagram.java
More file actions
49 lines (40 loc) · 1.39 KB
/
Copy pathGroupAnagram.java
File metadata and controls
49 lines (40 loc) · 1.39 KB
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
import java.util.*;
/*
* the sorting is used to transform each string into a canonical
* form that can be used as a key in the hash map. This ensures that all anagrams,
* which are words that can be rearranged to form each other, will have the same key.
* Canonical Form: The sorted string serves as a canonical form (key) for all anagrams.
*/
public class GroupAnagram {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0)
return new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] charArray = s.toCharArray();
Arrays.sort(charArray);
String sorted = new String(charArray);
if (!map.containsKey(sorted)) {
map.put(sorted, new ArrayList<>());
}
map.get(sorted).add(s);
}
return new ArrayList<>(map.values());
}
public boolean isAnagramn(String s1, String s2) {
if (s1.length() != s2.length())
return false;
int[] count = new int[26];
for (char c : s1.toCharArray()) {
count[c - 'a']++;
}
for (char c : s2.toCharArray()) {
count[c - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (count[i] != 0)
return false;
}
return true;
}
}