Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case.
本题开始做的时候,没有想到怎么让字母按照a-z的顺序排列,看了答案恍然大悟,有Arrays.sort这个方法函数。此题创建一个hashmap,key值来记录按照a-z顺序排好的字母,value值来记录只包含这些字母的链表。每遍历一个string,都将它转换成字符数组,然后排序后变回string看是否在map的key中包含它,代码如下:
1 public class Solution { 2 public List<List<String>> groupAnagrams(String[] strs) { 3 if(strs==null||strs.length==0) return null; 4 Map<String,List<String>> map = new HashMap<>(); 5 for(String str:strs){ 6 char[] ca = str.toCharArray(); 7 Arrays.sort(ca); 8 String s = String.valueOf(ca); 9 if(!map.containsKey(s)){ 10 List<String> list = new ArrayList<String>(); 11 map.put(s,list); 12 } 13 map.get(s).add(str); 14 } 15 return new ArrayList<List<String>>(map.values()); 16 } 17 }