-
Notifications
You must be signed in to change notification settings - Fork 0
/
group_anagrams_lc49.java
59 lines (56 loc) · 1.72 KB
/
group_anagrams_lc49.java
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
50
51
52
53
54
55
56
57
58
59
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
return solution1(strs);
/*
Runtime: 1753 ms, faster than 5.03% of Java online submissions for Group Anagrams.
Memory Usage: 178.3 MB, less than 5.00% of Java online submissions for Group Anagrams.
*/
}
private List<List<String>> solution1(Strings[] strs) {
List<List<String>> anagrams = null;
for (var str: strs) {
if (anagrams == null) {
anagrams = new ArrayList<>();
anagrams.add(createANewListForAnagramsWithString(str));
continue;
}
boolean strAdded = false;
for (var lst: anagrams) {
if(isAnagram(str, lst.get(0))) {
lst.add(str);
strAdded = true;
break;
}
}
if(!strAdded) {
anagrams.add(createANewListForAnagramsWithString(str));
strAdded = false;
}
}
return anagrams;
}
private List<String> createANewListForAnagramsWithString(String x) {
var l = new ArrayList<String>();
l.add(x);
return l;
}
private boolean isAnagram(String s, String t) {
if(s.length() != t.length()) {
return false;
}
char[] alpha = new char[26];
for (char c: s.toCharArray()) {
alpha[c-'a']++;
}
for (char c:t.toCharArray()) {
alpha[c-'a']--;
}
for (int i = 0; i< alpha.length; i++)
{
if(alpha[i] !=0) {
return false;
}
}
return true;
}
}