Leetcode: Anagrams

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

Note: All inputs will be in lower-case.

 

public ArrayList<String> anagrams(String[] strs) {
        // Start typing your Java solution below
        // DO NOT write main() function
        HashMap<String,ArrayList<String>> records = new HashMap<String, ArrayList<String>>();
        ArrayList<String> output = new ArrayList<String>();
        for(int i = 0; i<strs.length;i++){
            char[] charArr = strs[i].toCharArray();
            Arrays.sort(charArr);
            String sorted = new String(charArr);
            if(records.containsKey(sorted)){
                records.get(sorted).add(strs[i]);
            }else{
                ArrayList<String> strings = new ArrayList<String>();
                strings.add(strs[i]);
                records.put(sorted, strings);
            }
        }
        
        for(ArrayList<String> currArr : records.values()){
            if(currArr.size()>1){
                output.addAll(currArr);
            }    
        }    
        return output;
    }
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *