Saturday, May 30, 2015

[LeetCode] Anagrams

Anagrams

Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Solution: Sorting and HashMap.
public class Solution {
    private String sort(String s) {
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }
    
    public List<String> anagrams(String[] strs) {
        HashMap<String, ArrayList<String>> map = 
            new HashMap<String, ArrayList<String>>();
        for (String s : strs) {
            String str = sort(s);
            if (map.containsKey(str)) {
                map.get(str).add(s);
            } else {
                ArrayList<String> li = new ArrayList<String>();
                li.add(s);
                map.put(str, li);   
            }
        }
        
        ArrayList<String> list = new ArrayList<String>();
        Iterator iter = map.values().iterator();
        while (iter.hasNext()) {
            ArrayList<String> li = (ArrayList<String>)iter.next();
            if (li.size() > 1) {
                list.addAll(li);
            }
        }
        return list;
    }
}

No comments:

Post a Comment