面试题:乱序字符串

难度:中等

给出一个字符串数组S,找到其中所有的乱序字符串(Anagram)。如果一个字符串是乱序字符串,那么他存在一个字母集合相同,但顺序不同的字符串也在S中。

样例

对于字符串数组 ["lint","intl","inlt","code"]

返回 ["lint","inlt","intl"]

注意

所有的字符串都只包含小写字母

 

答案:

 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         ArrayList<String> result = new ArrayList<String>();
 8         HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
 9 
10         for (String str : strs) {
11             int[] count = new int[26];
12             for (int i = 0; i < str.length(); i++) {
13                 count[str.charAt(i) - 'a']++;
14             }
15 
16             int hash = getHash(count);
17             if (!map.containsKey(hash)) {
18                 map.put(hash, new ArrayList<String>());
19             }
20 
21             map.get(hash).add(str);
22         }
23 
24         for (ArrayList<String> tmp : map.values()) {
25             if (tmp.size() > 1) {
26                 result.addAll(tmp);
27             }
28         }
29 
30         return result;
31     }
32     private int getHash(int[] count) {
33         int hash = 0;
34         int a = 378551;
35         int b = 63689;
36         for (int num : count) {
37             hash = hash * a + num;
38             a = a * b;
39         }
40         return hash;
41     }
42 }

 

posted @ 2015-08-29 12:14  -小城-  阅读(307)  评论(0编辑  收藏  举报