乱序字符串
题目
给出一个字符串数组S,找到其中所有的乱序字符串(Anagram)。如果一个字符串是乱序字符串,那么他存在一个字母集合相同,但顺序不同的字符串也在S中。
注意事项
所有的字符串都只包含小写字母样例
对于字符串数组 [“lint”,”intl”,”inlt”,”code”]
返回 [“lint”,”inlt”,”intl”]题解
由于不同顺序字符串的hash值是不同的,所以先对所有字符串进行处理,把所有字母出现的次数存入数组,这样所有顺序不同的字符串对应的数组是完全相同的。再对数组用RSHash法进行处理,将hash值存入hashmap,最后遍历一次hashmap即可。
public class Solution {
/**
* @param strs: A list of strings
* @return: A list of strings
*/
public List<String> anagrams(String[] strs) {
ArrayList<String> result = new ArrayList<String>();
HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
for (String str : strs)
{
int[] count = new int[26];
for (int i = 0; i < str.length(); i++)
{
count[str.charAt(i) - 'a']++;
}
int hash = rsHash(count);
if (!map.containsKey(hash))
{
map.put(hash, new ArrayList<String>());
}
map.get(hash).add(str);
}
for (ArrayList<String> tmp : map.values())
{
if (tmp.size() > 1)
{
result.addAll(tmp);
}
}
return result;
}
private int rsHash(int[] count)
{
int hash = 0;
int a = 378551;
int b = 63689;
for (int num : count)
{
hash = hash * a + num;
a = a * b;
}
return hash;
}
}
Last Update 2016.10.25