Skip to content

Commit 00e33af

Browse files
medium String sorting char map values arraylist
49. Group Anagrams Solved Medium Topics Companies Given an array of strings strs, group the anagrams together. You can return the answer in any order. Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] Explanation: There is no string in strs that can be rearranged to form "bat". The strings "nat" and "tan" are anagrams as they can be rearranged to form each other. The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other. Example 2: Input: strs = [""] Output: [[""]] Example 3: Input: strs = ["a"] Output: [["a"]] Constraints: 1 <= strs.length <= 104 0 <= strs[i].length <= 100 strs[i] consists of lowercase English letters. Seen this question in a real interview before? 1/5 Yes No Accepted 3.3M Submissions 4.7M Acceptance Rate 69.7% Topics Array Hash Table String Sorting
1 parent 1c29255 commit 00e33af

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

group-anagrams.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public List<List<String>> groupAnagrams(String[] strs) {
3+
Map<String,List<String>> ans=new HashMap<>();
4+
for(String s:strs){
5+
char[] c=s.toCharArray();
6+
Arrays.sort(c);
7+
String key=new String(c);
8+
if(!ans.containsKey(key)){
9+
ans.put(key,new ArrayList<>());
10+
}
11+
ans.get(key).add(s);
12+
}
13+
return new ArrayList<>(ans.values());
14+
}
15+
}
16+
17+
18+
19+
// class Solution {
20+
// public List<List<String>> groupAnagrams(String[] strs) {
21+
// Map<String,List<String>> ans=new HashMap<>();
22+
// for(String s:strs){
23+
// int[] count=new int[26];
24+
// for(char c:s.toCharArray()){
25+
// count[c-'a']++;
26+
// }
27+
// StringBuilder sb=new StringBuilder();
28+
// for(int num:count){
29+
// sb.append(num).append("#");
30+
// }
31+
// String key=sb.toString();
32+
// if(!ans.containsKey(key)){
33+
// ans.put(key,new ArrayList<>());
34+
// }
35+
// ans.get(key).add(s);
36+
// }
37+
// return new ArrayList<>(ans.values());
38+
// }
39+
// }

0 commit comments

Comments
 (0)