給定一個字符串數組,將相同字謎組合在一塊兒。(字謎是指顛倒字母順序而成的字)
例如,給定 ["eat", "tea", "tan", "ate", "nat", "bat"],返回:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
注意:全部的輸入都是小寫的。
詳見:https://leetcode.com/problems/group-anagrams/description/html
Java實現: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數組