Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created November 5, 2018 06:53
Show Gist options
  • Save shixiaoyu/50381a3e769b8945ade22eac239f8a47 to your computer and use it in GitHub Desktop.
Save shixiaoyu/50381a3e769b8945ade22eac239f8a47 to your computer and use it in GitHub Desktop.
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> res = new ArrayList<>();
if (strs == null || strs.length == 0) {
return res;
}
Map<String, List<String>> lookup = new HashMap<>();
for (String s : strs) {
String sortedStr = this.sortString(s);
if (lookup.containsKey(sortedStr)) {
lookup.get(sortedStr).add(s);
} else {
List<String> list = new ArrayList<>();
list.add(s);
lookup.put(sortedStr, list);
}
}
for (Map.Entry<String, List<String>> entry : lookup.entrySet()) {
List<String> l = entry.getValue();
Collections.sort(l);
res.add(l);
}
return res;
}
private String sortString(String s) {
char[] a = s.toCharArray();
Arrays.sort(a);
// Need to create a new instance
return new String(a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment