049 Group Anagrams 字谜分组
给定一个字符串数组,将相同字谜组合在一起。(字谜是指颠倒字母顺序而成的字)
例如,给定 ["eat", "tea", "tan", "ate", "nat", "bat"],返回:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
注意:所有的输入都是小写的。
详见:https://leetcode.com/problems/group-anagrams/description/
Java实现:
class Solution { public List<List<String>> groupAnagrams(String[] strs) { List<List<String>> res = new ArrayList<List<String>>(); int size = strs.length; if(size<1){ return res; } Map<String,List<String>> map = new HashMap<String,List<String>>(); String tmp = ""; for(int i=0;i<size;i++){ tmp = strs[i]; char[] arrayOfString = tmp.toCharArray(); Arrays.sort(arrayOfString); tmp = new String(arrayOfString); if(map.containsKey(tmp)){ map.get(tmp).add(strs[i]); }else{ List<String> item = new ArrayList<String>(); item.add(strs[i]); map.put(tmp, item); } } for (List<String> value : map.values()) { res.add(value); } return res; } }
参考:https://www.cnblogs.com/grandyang/p/4385822.html