Skip to content

Instantly share code, notes, and snippets.

@hsaputra
Created October 2, 2018 23:29
Show Gist options
  • Save hsaputra/25c340a82892fdeab0985b3dd35d44f4 to your computer and use it in GitHub Desktop.
Save hsaputra/25c340a82892fdeab0985b3dd35d44f4 to your computer and use it in GitHub Desktop.
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0)
return new LinkedList<List<String>>();
Map<String, List<String>> superAnagrams = new HashMap<>();
int sLen = strs.length;
for (String str : strs) {
// Sort
char[] asChars = str.toCharArray();
Arrays.sort(asChars);
String sortedStr = new String(asChars);
List<String> anagrams = null;
if (!superAnagrams.containsKey(sortedStr)) {
anagrams = new LinkedList<String>();
superAnagrams.put(sortedStr, anagrams);
} else {
anagrams = superAnagrams.get(sortedStr);
}
anagrams.add(str);
}
List<List<String>> results = new LinkedList<List<String>>(superAnagrams.values());
return results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment