Created
November 5, 2018 06:53
-
-
Save shixiaoyu/50381a3e769b8945ade22eac239f8a47 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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