2.12 Group Anagrams

Description

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return:

[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]

Method

use hashmap to store the strings which have the same characters.

Time and Space Complexity

o(n * len)

Code

public class Solution {

 public List<List<String>> groupAnagrams(String[] strs) {
       if (strs == null || strs.length == 0){
           return null;
       }

       HashMap<String,List<String>> map = new HashMap<String,List<String>>();
       for (String s : strs){
            char[] cs = s.toCharArray();
            Arrays.sort(cs);
            String key = new String(cs);
            if (map.containsKey(key)){
                map.get(key).add(s);
            } else {
                List<String> list = new ArrayList<String>();
                list.add(s);
                map.put(key, list);
            }
       }
       for (String key : map.keySet()){
           Collections.sort(map.get(key));
       }
       return new ArrayList<List<String>>(map.values());
}

}

results matching ""

    No results matching ""