Sunday, April 6, 2014

Leetcode: Anagrams

Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.

Solution:

We can sort each string and store it in a hashmap to identify when a string has an anagram. The algorithm runs inO(n k log k). 

public class Solution {
    public ArrayList<String> anagrams(String[] strs) {
        ArrayList<String> sol = new ArrayList<String>();
        HashMap<String, String> map = new HashMap<String, String>();
        for(int i= 0; i< strs.length; i++)
        {
            char[] tempArr = strs[i].toCharArray();
            Arrays.sort(tempArr);
            String temp = new String(tempArr);
            if(map.containsKey(temp))
            {
                sol.add(strs[i]);
                if(map.get(temp)!=null)
                {
                    sol.add(map.get(temp));
                    map.put(temp,null);
                }
            }
            else
                map.put(temp,strs[i]);
        }
        return sol;
    }
}

No comments :

Post a Comment