Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

49. Group Anagrams

Posted on 2020-07-01 | Edited on 2021-01-22

LeetCode

Approach 1: Categorize by Sorted String, Time Complexity: O(NKlogK)

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> map=new HashMap<>();
for(String str:strs){
char[] chs=str.toCharArray();
Arrays.sort(chs);
String newStr=new String(chs);
if(!map.containsKey(newStr)) map.put(newStr,new ArrayList(Arrays.asList(str)));
else map.get(newStr).add(str);
}
return new ArrayList(map.values());
}
}

Approach 2: Categorize by Count, Time Complexity: O(NK)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0) return new ArrayList();
Map<String, List> ans = new HashMap<String, List>();
int[] count = new int[26];
for (String s : strs) {
Arrays.fill(count, 0);
for (char c : s.toCharArray()) count[c - 'a']++;

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 26; i++) sb.append(count[i]);

String key = sb.toString();
if (!ans.containsKey(key)) ans.put(key, new ArrayList());
ans.get(key).add(s);
}
return new ArrayList(ans.values());
}
}

<1…119120121…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%