Group Anagrams(Medium)

Given an array of strings, group anagrams together.

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

Return

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]
  • For the return value, each inner list's elements must follow the lexicographic order.
  • All inputs will be in lower-case.
public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> ans = new ArrayList<>();
        if (strs==null || strs.length==0) { return ans; }
        Arrays.sort(strs);

        Map<String, List<String>> map = new HashMap<>();
        for (String s: strs) {
            char[] sCharArr = s.toCharArray();
            Arrays.sort(sCharArr);
            String key = new String(sCharArr);
            List<String> list = map.get(key);
            if (list == null) {
                List<String> temp = new ArrayList<>();
                temp.add(s);
                map.put(key, temp);
            } else { list.add(s); }
        }

       for (List<String> l : map.values()) {
           Collections.sort(l);
           ans.add(l);
       }
        return ans;
    }

results matching ""

    No results matching ""