按照单词的字母是否相同对字符串数组进行分组

https://blog.csdn.net/Lynn_Baby/article/details/80790796

题目描述:

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

Note: All inputs will be in lower-case.

思路解析:

1.首先判空
2.创建元素类型为ArrayList(String)的ArrayList作为结果res,创建元素类型为(String,ArrayList(String))的HashMap
3.遍历strs,把每个字符串Arrays.sort以后,再分组存入HashMap
4.遍历HashMap的values,存入res,返回res

代码:

    public static void main(String[] args) throws IOException {
        String[] strs = {"a","acb","bca","aabcd","abcdefgh","abdca"};
        ArrayList<ArrayList<String>> res = anagrams(strs);
        System.out.println(res);
        //[[acb, bca], [aabcd, abdca], [a], [abcdefgh]]

}
    //按照单词的字母是否相同对字符串数组进行分组
    public static ArrayList<ArrayList<String>> anagrams(String[] strs) {
        ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
        if(strs==null || strs.length==0){
            return res;
        }
        HashMap<String,ArrayList<String>> hm = new HashMap<String,ArrayList<String>>();
        for(String s : strs){
            char[] ch = s.toCharArray();
            Arrays.sort(ch);
            String temp = new String(ch);
            if(hm.containsKey(temp)){
               hm.get(temp).add(s);
               hm.put(temp, hm.get(temp));

            }else{
                ArrayList<String> templist = new ArrayList<String>();
                templist.add(s);
                hm.put(temp,templist);
            }
        }
        Collection<ArrayList<String>> values=hm.values();
        for(Iterator it=values.iterator();it.hasNext();){
            res.add((ArrayList<String>)it.next());
        }
        return res;
    }

猜你喜欢

转载自blog.csdn.net/junjunba2689/article/details/82622951