Monday, July 13, 2015

Anagrams

Given an array of strings, return all groups of strings that are anagrams.
Have you met this question in a real interview? 
Yes
Example
Given ["lint", "intl", "inlt", "code"], return["lint", "inlt", "intl"].
Given ["ab", "ba", "cd", "dc", "e"], return["ab", "ba", "cd", "dc"].

Note
All inputs will be in lower-case

public class Solution {
    /**
     * @param strs: A list of strings
     * @return: A list of strings
     */
    public List<String> anagrams(String[] strs) {
        // write your code here
        HashMap<String, ArrayList<String>> record = new HashMap<String, ArrayList<String>>();
        List<String> res = new ArrayList<String>();
        
        for(String s : strs){
            char[] arr = s.toCharArray();
            Arrays.sort(arr);
            String newWord = new String(arr);
            if(!record.containsKey(newWord)){
                record.put(newWord, new ArrayList<String>());
            }
             record.get(newWord).add(s);
        }
        
        for(String s : record.keySet()){
            if(record.get(s).size() > 1){
                res.addAll(record.get(s));
            }
        }
        return res;
        
    }
}

No comments:

Post a Comment