Anagrams

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

 Notice

All inputs will be in lower-case

Example

Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"].

Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"].

Analysis:

If there is only one group of anagrams, it is very easy. However, as we need to find all groups of anagrams, it is not easy to do it. The idea is we first sort all the strings, and add it to hashmap. If the string exists in the hashmap, we will add the string to the value (which is a list) of the key.

 1 public class Solution {
 2     /**
 3      * @param strs: A list of strings
 4      * @return: A list of strings
 5      */
 6     public List<String> anagrams(String[] strs) {
 7         HashMap<String, ArrayList<String>> record = new HashMap<String, ArrayList<String>>();
 8         List<String> res = new ArrayList<String>();
 9         
10         for(String s : strs){
11             char[] arr = s.toCharArray();
12             Arrays.sort(arr);
13             String newWord = new String(arr);
14             if(!record.containsKey(newWord)){
15                 record.put(newWord, new ArrayList<String>());
16             }
17              record.get(newWord).add(s);
18         }
19         
20         for(String s : record.keySet()){
21             if(record.get(s).size() > 1){
22                 res.addAll(record.get(s));
23             }
24         }
25         return res;
26     }
27 }

 

 

posted @ 2016-07-16 00:22  北叶青藤  阅读(210)  评论(0编辑  收藏  举报