Anagrams

Anagrams
 1 public class Solution {
 2     public ArrayList<String> anagrams(String[] strs) {
 3         int len = strs.length;
 4         HashMap<String,ArrayList<String>> hm = new HashMap<String,ArrayList<String>>();
 5         ArrayList<String> res = new ArrayList<String>();
 6         for(int i=0;i<len;i++){
 7             String sort = sort(strs[i]);
 8             if(hm.containsKey(sort)){
 9                 hm.get(sort).add(strs[i]);
10             }
11             else{
12                 ArrayList<String> temp = new ArrayList<String>();
13                 temp.add(strs[i]);
14                 hm.put(sort,temp);
15             }
16         }
17         Iterator it = hm.values().iterator();
18         while(it.hasNext()){
19             ArrayList<String> temp = (ArrayList<String>)it.next();
20             if(temp.size()>1){
21                res.addAll(temp);
22             }
23         }
24         return res;
25     }
26     public String sort(String s){
27         char [] c = s.toCharArray();
28         Arrays.sort(c);
29         return new String(c);
30     }
31 }
View Code

Anagrams

上一篇:Permutation Sequence


下一篇:Insert Interval