Anagrams, anagramsleetcode
This article is in the study of the summary, welcome to reprint but please note the Source: http://blog.csdn.net/pistolove/article/details/42744709
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Ideas:
(1) If you do not know the meaning of anagrams, it is easy to understand the meaning of the question. At first, I understood how many types of string arrays are arranged in full. OJ was wrong several times, and was forced to look up the meaning of anagrams to know, anagrams: A word [Phrase] consisting of an inverted alphabetic order. It seems that English is better to learn. Given a string array, obtain all the string sequences of the same characters in the array. For example, if the string array ["abc", "acb", "cab", "xyz", "fg"] is specified, the result is ["abc", "acb ", "cab"].
(2) This article mainly uses Map for storage, where the Key is the sorted string (by sorting the string, the strings with disordered order can be changed to the same ), value is a series of strings that disrupt the order. In the preceding example, the key is "abc" and the value is ["abc", "acb", "cab"]. Then, judge whether the number of elements in the List corresponding to the value in the Map is greater than 1. If the number is greater than 1, it indicates that there are multiple strings consisting of the same characters but the order is disrupted.
(3) See the code below. Hope to help you. (PS: The Arrays. sort () method sorts the given array)
The algorithm code is implemented as follows:
/** * * @author liqq */public static List<String> anagrams(String[] strs) {if (strs == null || strs.length < 2)return new ArrayList<String>();Map<String, List<String>> maps = new HashMap<String, List<String>>();for (String str : strs) {char[] arr = str.toCharArray();Arrays.sort(arr);String key = new String(arr);if (!maps.containsKey(key)) {maps.put(key, new ArrayList<String>());}List<String> list = maps.get(key);list.add(new String(str));}List<String> result = new ArrayList<String>();for (Iterator<String> iterator = maps.keySet().iterator(); iterator.hasNext();) {String key = iterator.next();if (maps.get(key).size() > 1) {result.addAll(maps.get(key));}}return result;}