Skip to content

Commit 73e3f94

Browse files
committed
Added java solution for 049_Group_Anagrams.java
1 parent e686121 commit 73e3f94

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

java/049_Group_Anagrams.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public List<List<String>> groupAnagrams(String[] strs) {
3+
int[][] alphabets = new int[strs.length]['z' - 'a' + 1];
4+
5+
for(int i = 0; i < strs.length; i++) {
6+
String str = strs[i];
7+
8+
for(int j = 0; j < str.length(); j++)
9+
alphabets[i][str.charAt(j) - 'a']++;
10+
}
11+
12+
boolean[] visited = new boolean[strs.length];
13+
14+
List<List<String>> answer = new ArrayList<>();
15+
16+
for(int i = 0; i < strs.length; i++) {
17+
if(visited[i]) continue;
18+
19+
List<String> list = new ArrayList<>();
20+
21+
for(int j = i; j < strs.length; j++) {
22+
if(visited[j]) continue;
23+
if(isAnagram(alphabets[i], alphabets[j])) {
24+
list.add(strs[j]);
25+
visited[j] = true;
26+
}
27+
}
28+
29+
answer.add(list);
30+
}
31+
32+
return answer;
33+
}
34+
35+
public boolean isAnagram(int[] arr1, int[] arr2) {
36+
for(int i = 0; i < arr1.length; i++) {
37+
if(arr1[i] != arr2[i])
38+
return false;
39+
}
40+
return true;
41+
}
42+
}

0 commit comments

Comments
 (0)