171.Anagrams-乱序字符串(中等题)

乱序字符串

  1. 题目

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

    注意事项
    所有的字符串都只包含小写字母

  2. 样例

    对于字符串数组 [“lint”,”intl”,”inlt”,”code”]
    返回 [“lint”,”inlt”,”intl”]

  3. 题解

    由于不同顺序字符串的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值