Skip to content

Instantly share code, notes, and snippets.

@Lugriz
Last active February 11, 2020 19:07
Show Gist options
  • Save Lugriz/c4499c09174391af48129c1ace71f189 to your computer and use it in GitHub Desktop.
Save Lugriz/c4499c09174391af48129c1ace71f189 to your computer and use it in GitHub Desktop.
approach en java
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('#');
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());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment