首页 > 代码库 > Anagrams

Anagrams

题目

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

Note: All inputs will be in lower-case.

方法

题目中是找出所有的字符串由相同的字符组成,只是顺序不同。
    public List<String> anagrams(String[] strs) {
        List<String> list = new ArrayList<String>();
        if (strs == null || strs.length == 0) {
            return list;
        }
        int len = strs.length;
        HashMap<String, ArrayList<String>> hashMap = new HashMap<String, ArrayList<String>>();
        for (int i = 0; i< len; i++) {
            char[] ch = strs[i].toCharArray();
            Arrays.sort(ch);
            String str = new String(ch);
            if (hashMap.containsKey(str)) {
                hashMap.get(str).add(strs[i]);
            } else {
                ArrayList<String> arr = new ArrayList<String>();
                arr.add(strs[i]);
                hashMap.put(str, arr);
            }
        }
        
        Iterator<ArrayList<String>> ite = hashMap.values().iterator();
        while(ite.hasNext()) {  
            ArrayList<String> item = ite.next();  
            if(item.size()>1)  
                list.addAll(item);  
        } 
        return list;
    }