Leetcode–Anagrams

The Problem:

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

Note: All inputs will be in lower-case.

Notes:

  1. The key is to sort each string, and use sorted string as the signature to group anagrams.
  2. Use a hashMap to record the list of each group. We can also directly add the anagrams to result list (with some mark to tell if a key in the map has no anagram) since we don’t need to return the result by groups

Java Solution

public class Solution {
    public List<String> anagrams(String[] strs) {
        List<String> result = new ArrayList<String>();
        if(strs.length==0) return result;
        Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
        for(int i = 0; i < strs.length; i++){
            char[] arr = strs[i].toCharArray();
            Arrays.sort(arr);
            String newstr = new String(arr);
            if(!map.containsKey(newstr)){
                map.put(newstr, new ArrayList<String>());
            }
            map.get(newstr).add(strs[i]);
        }
        for(ArrayList<String> list : map.values()){
            if(list.size()>=2){
                for(String s : list)
                    result.add(s);
            }
        }
        return result;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s