a simple Java solution


  • 1
    1. for each string, sort it's char array, and use it as a key.
    2. put a empty list as value of that 'key'
    3. append strings with the same key to the value list
    4. dump the values of map to list
    public class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            HashMap<String, List<String>> map = new HashMap<String, List<String>>();
            List<List<String>> result = new ArrayList<List<String>>();
            for(String s : strs) {
                char[] ch = s.toCharArray();
                Arrays.sort(ch);
                String key = new String(ch);
                if(!map.containsKey(key)){
                    map.put(key, new ArrayList<String>());
                }
                map.get(key).add(s);
            }
            
            for(List<String> l : map.values()) {
                result.add(l);
            }
            
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.