发布时间:2017-2-21 2:00:02 编辑 分享查询网我要评论

Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be in lower-case. Analysis: Using a hash table groups all anagrams together. We can sort each string first and using such sorted string as the key to store it in the hash table.  public class Solution { public ArrayList<String> anagrams(String[] strs) { ArrayList<String> res = new ArrayList<String>(); HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(); for(int i=0; i<strs.length; i++) { char[] charArray = strs[i].toCharArray(); Arrays.sort(charArray); String sortedString = new String(charArray); if(!map.containsKey(sortedString)) map.put(sortedString, new ArrayList<String>()); map.get(sortedString).add(strs[i]); } for(String s : map.keySet()) { if(map.get(s).size()>1) res.addAll(map.get(s)); // return groups only } return res; } }

下一篇:sdut2125 串结构练习——字符串匹配(strstr求子串)


关键词: Anagrams