My 31ms Java Solution


  • 0
    public class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            List<List<String>> res = new ArrayList<List<String>>();
            if (strs == null || strs.length == 0) {
                return res;
            }
            HashMap<String, Integer> map = new HashMap<String, Integer>();
            for (String str : strs) {
                char[] array = str.toCharArray();
                Arrays.sort(array);
                if (!map.containsKey(String.valueOf(array))) {
                    res.add(new ArrayList<String>());
                    map.put(String.valueOf(array), res.size() - 1);
                } 
                int pos = map.get(String.valueOf(array));
                res.get(pos).add(str);
            }
            return res;
        }
    }
    

Log in to reply
 

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