Created
October 2, 2018 23:29
-
-
Save hsaputra/25c340a82892fdeab0985b3dd35d44f4 to your computer and use it in GitHub Desktop.
Group Anagrams - https://leetcode.com/problems/group-anagrams/description/
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
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