Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
We sort each string in alphabet order, then each anagrams would have the same result. We could use this as the key to group all the anagrams in a hashmap. The time complexity of this method would be O(n*mlogm) where m is the average length of all strings. A better way is to use count sort of the strings since there are only 26 characters of them. The time complexity would reduce to O(n*m).public ArrayList<String> anagrams(String[] strs) { HashMap<String, List<String>> map = new HashMap<String, List<String>>(); for(int i = 0; i < strs.length; i++) { char[] chs = strs[i].toCharArray(); Arrays.sort(chs); String str = new String(chs); if(map.containsKey(str) == true) { map.get(str).add(strs[i]); } else { List<String> list = new ArrayList<String>(); list.add(strs[i]); map.put(str, list); } } ArrayList<String> res = new ArrayList<String>(); for(String key : map.keySet()) { if(map.get(key).size() > 1) { for(String str : map.get(key)) res.add(str); } } return res; }
没有评论:
发表评论