JAVA sort and HashMap approach but using <String, Integer>

  • 0
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        if (strs == null || strs.length == 0) {
            return res;
        Map<String, Integer> m = new HashMap<>();
        for (String str : strs) {
            String sortedStr = sortString(str);
            if (m.containsKey(sortedStr)) {
                int index = m.get(sortedStr);
            } else {
                m.put(sortedStr, res.size());
                List<String> group = new ArrayList<>();
        return res;
    private String sortString (String str) {
        char[] chars = str.toCharArray();
        return new String(chars);

    HashMap records where the certain anagram group is at in the result list. This eliminates the work to go through the values of HashMap if we used <String, List<string>> instead

Log in to reply

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