Anagrams

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

Solution and Precautions:

First, note what is Anagrams, you can google search it and let’s claim that word A and B is called anagram to each other if we can get word B(A) from A(B)  by rearranging the letters of A(B) to produce B(A), using all the original letters exactly once.

Then, one straightforward way is to compare each pair of words and to see if they are anagrams, my first try is just like this, starting from the first word, I search through all the remaining words and get its corresponding anagrams (to the first word), of course, all such anagrams we found for the first word won’t be anagrams to any other words so we don’t have to consider them for further check. This method could pass the small data set test but will get TLE for large dataset test. The time complexity is O(N^2 * K log K) where N is the number of words and K is the length of the longest word, or you may say the average length of the words.

Finally, if we think deeper into this, we will find that we actually don’t have to do the N^2 comparisons at all. The key observation is that A and B is anagram to each other if and only if their sorted form are exactly the same. As a result, one linear scan through the words list is enough, for each word we can get its sorted form in K log K time, and we can use map to store the groups of words which are in the same sorted form. The time complexity is O(N K log K), this approach could pass both small data test and large data test.

 1 public class Solution {
 2     public ArrayList<String> anagrams(String[] strs) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         int len = strs.length;
 5         ArrayList<String> result = new ArrayList<String>();
 6         HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
 7         for(int i = 0; i < strs.length; i ++){
 8             char[] cs = strs[i].toCharArray();
 9             Arrays.sort(cs);
10             String tmp = String.valueOf(cs);
11             if(!map.containsKey(tmp)) map.put(tmp, new ArrayList<String>());
12             map.get(tmp).add(strs[i]);
13         }
14         Iterator iter = map.values().iterator();
15         while(iter.hasNext()){
16             ArrayList<String> list = (ArrayList<String>)iter.next();
17             if(list.size() > 1){
18                 result.addAll(list);
19             }
20         }
21         return result;
22     }
23 }
原文地址:https://www.cnblogs.com/reynold-lei/p/3412295.html