Java with hashmaps. How can I improve this solutions? Any suggestions are welcome.


  • 0
    A
    public List<List<String>> groupAnagrams(String[] strs) {
            Map<String, List<String>> map = new HashMap<>();
            Arrays.sort(strs);
            for (String str : strs) {
                char[] chars = str.toCharArray();
                Arrays.sort(chars);
                String sorted = new String(chars);
                if (map.containsKey(sorted)) {
                    map.get(sorted).add(str);
                }
                else {
                	List<String> list = new ArrayList<>();
                	list.add(str);
                    map.put(sorted, list);
                }
            }
            List<List<String>> result = new ArrayList<>(map.values());
            return result;
        }

Log in to reply
 

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