Leetcode: Group Anagrams
Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of your output does not matter.
if want lexicographic order,然后要用Collections.sort() 来保证字典序
for (List<String> each : map.values()) {
Collections.sort(each);
res.add(new ArrayList<String>(each));
}
1 class Solution { 2 public List<List<String>> groupAnagrams(String[] strs) { 3 List<List<String>> res = new ArrayList<>(); 4 HashMap<String, List<String>> map = new HashMap<>(); 5 6 for (String str : strs) { 7 char[] arr = str.toCharArray(); 8 Arrays.sort(arr); 9 String sorted = Arrays.toString(arr); 10 // if (!map.containsKey(sorted)) map.put(sorted, new ArrayList<String>()); 11 map.putIfAbsent(sorted, new ArrayList<String>()); 12 map.get(sorted).add(str); 13 } 14 15 for (List<String> value : map.values()) { 16 res.add(value); 17 } 18 return res; 19 } 20 }