Skip to content

Instantly share code, notes, and snippets.

@ozkansari
Created April 12, 2020 20:34
Show Gist options
  • Save ozkansari/b69f7dcad853a6bdd2ed3b4e5232bf7e to your computer and use it in GitHub Desktop.
Save ozkansari/b69f7dcad853a6bdd2ed3b4e5232bf7e to your computer and use it in GitHub Desktop.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
class GroupAnagrams2 {
public List<List<String>> groupAnagrams(String[] wordsArray) {
Map<String,List<String>> anagramWords = new HashMap<>();
for(String word : wordsArray) {
String key = calculateKey(word);
List<String> wordList = anagramWords.get(key);
if(wordList == null) {
wordList = new ArrayList<String>();
anagramWords.put(key, wordList);
}
wordList.add(word);
}
return anagramWords.values().stream().collect(Collectors.toList());
}
private String calculateKey(String word) {
// We know word is all lowercase. Otherwise we can convert it to lowercase.
// word = word.toLowerCase();
char [] sortedChars = word.toCharArray();
Arrays.sort(sortedChars);
return new String(sortedChars);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment