Thursday, January 8, 2015

LeetCode 49: Anagrams

Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
public class Solution {
    public List<String> anagrams(String[] strs) {
        // For example, "eat" and "tea" are anagrams
        // The same characters and number but different order.
        
        // Firstly sort strings
        // Save the indices of the same anagram into HashMap
        
        // String - sorted string; List<Integer> - corresponding indices
        Map<String, List<Integer>> map = new HashMap<>();
        
        for (int i = 0; i < strs.length; i++)
        {
            String sortedStr = sort(strs[i]);
            
            if (!map.containsKey(sortedStr))
            {
                List<Integer> index = new LinkedList<>();
                index.add(i);
                map.put(sortedStr, index);
            }
            else
                map.get(sortedStr).add(i);
        }
        
        List<String> result = new LinkedList<>();
        
        for (String strKey : map.keySet())
        {
            if (map.get(strKey).size() == 1)
                continue;
                
            for (int j = 0; j < map.get(strKey).size(); j++)
                result.add(strs[map.get(strKey).get(j)]); // Can't use remove(j), first time is Ok, next time j is changed.
        }
        
        return result;
    }
    
    private String sort(String str)
    {
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }
}

No comments:

Post a Comment