[Leetcode] Anagrams

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

Note: All inputs will be in lower-case.

Solution:

http://www.cnblogs.com/AnnieKim/archive/2013/04/25/3041982.html

 1 public class Solution {
 2     public List<String> anagrams(String[] strs) {
 3         List<String> result = new ArrayList<String>();
 4     
 5         HashMap<String, Integer> hm = new HashMap<String, Integer>();
 6         for (int i = 0; i < strs.length; ++i) {
 7             String s = strs[i];
 8             s = sort(s);
 9             if (hm.containsKey(s)) {
10                 if (hm.get(s) >= 0) {
11                     result.add(strs[hm.get(s)]);
12                     hm.put(s, -1);
13                 }
14                 result.add(strs[i]);
15             } else {
16             
17                 hm.put(s, i);
18             }
19         }
20         return result;
21     }
22 
23     private String sort(String s) {
24         // TODO Auto-generated method stub
25         if (s.length() != 0) {
26             char[] c_s = s.toCharArray();
27             Arrays.sort(c_s);
28             return new String(c_s);
29         }
30         else
31             return "";
32     }
33 }
原文地址:https://www.cnblogs.com/Phoebe815/p/4100964.html