Given an array of strings, group anagrams together.
For example, given:
Return:
["eat", "tea", "tan", "ate", "nat", "bat"]
,Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case.
Solution:
If two strings s1 and s2 are anagram, sort(s1) will be equal to sort(s2). So we can use sorted element as a key to the HashMap.
We go through the input array. For each s, we sort it and check if the HashMap has this key. If so, s is an anagrams and we put it to corresponding value list.
Code:
public class Solution { public List<List<String>> groupAnagrams(String[] strs) { if (strs == null || strs.length == 0) { return new ArrayList<List<String>>(); } HashMap<String, List<String>> map = new HashMap<>(); for (String str : strs) { char[] charArr = str.toCharArray(); Arrays.sort(charArr); String s = new String(charArr); if (!map.containsKey(s)) { map.put(s, new ArrayList<String>()); } map.get(s).add(str); } return new ArrayList<List<String>>(map.values()); } }