Created
April 12, 2020 20:34
-
-
Save ozkansari/b69f7dcad853a6bdd2ed3b4e5232bf7e to your computer and use it in GitHub Desktop.
Given an array of strings, group anagrams together. https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3288/
This file contains 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
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