Anagrams lintcode

时间:2016-01-16 16:45:12

标签: java

  

给定一个字符串数组,返回所有字符串组,即字谜。

     

给定[“lint”,“intl”,“inlt”,“code”],返回[“lint”,“inlt”,“intl”]。

     

鉴于[“ab”,“ba”,“cd”,“dc”,“e”],返回[“ab”,“ba”,“cd”,“dc”]。

我的代码是这样的,但它在"stringb.add(aString));"给出了错误消息;我无法弄清楚原因。

{
    /**
     * @param strs: A list of strings
     * @return: A list of strings
     */

    private int hash(int[] count){
        int hash = 0;
        int primeA = 378551;
        int primeB = 378559;
        //int result = 0;
        for(int aNumber: count){
            hash = hash*primeA + aNumber;
            primeA = primeA*PrimeB;
        }
    } 
    public List<String> anagrams(String[] strs) {
        // write your code here
        int i = 0;
        int l = 0;
        ArrayList<String> result = new ArrayList<String>();
        Map<Integer, ArrayList<String>> strings  = new HashMap<Integer, ArrayList<String>>();

        for(String aString : strs){
            int[] charCount = new int[26];
            for(i = 0; i<aString.length(); i++){
                charCount[aString.charAt[i]-'a']++;
            }
            l = hash(charCount);
            if(!strings.containsKey(l)){
                strings.put(l,new ArrayList<String>());
            }
            ArrayList<String> stringb = strings.get(l);
            stringb.add(aString));

        }
        for(ArrayList<String> aList: strings.values()){
                if(aList.size()>1){
                    result.addAll(aList);
                }
        }
        result result;
    }
}

0 个答案:

没有答案