字母异位词分组

49. 字母异位词分组

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

说明:

  • 所有输入均为小写字母。
  • 不考虑答案输出的顺序。

题解:
本体主要考察的是对hashmap的用法:
首先,看到了字母排序不同我们就可以猜想到用hashmap,那么如何用hashmap来解决这个问题呢?我们可以对字符串中各字母的个数进行计数,如果每个字母出现的次数都一样则代表两个字符串是异位词。

 public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> result = new ArrayList<>();
        HashMap<HashMap<Character, Integer>, List<String>> map = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            String str = strs[i];
            HashMap<Character, Integer> characterIntegerHashMap = scanWord(str);
            if (!map.containsKey(characterIntegerHashMap)) {
                map.put(characterIntegerHashMap, new ArrayList<>());
            }
            map.get(characterIntegerHashMap).add(str);
        }
        for (List list:
             map.values()) {
            result.add(list);
        }
        return result;
    }

    private HashMap<Character, Integer> scanWord(String str) {
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < str.length(); i++) {
            map.put(str.charAt(i), map.getOrDefault(str.charAt(i), 0) + 1);
        }
        return map;
    }

这种方法效率有点低,而且内存占用也高。

还有一种方法就是对字符串的字符排序,然后进行比较。

public List<List<String>> groupAnagrams2(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            char[] chars = strs[i].toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            List<String> list = map.getOrDefault(key, new ArrayList<>());
            list.add(strs[i]);
            map.put(key, list);
        }
        return new ArrayList<>(map.values());
    }

总而言之,都是对hashmap使用的考察。

本题出自leetcode:https://leetcode-cn.com/problems/group-anagrams/

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • LeetCode题目链接链接 https://leetcode-cn.com/problems/group-ana...
    Mastergad阅读 372评论 0 0
  • 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 示例: 输入: ["eat...
    滨岩阅读 461评论 0 0
  • 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 示例: 输入: ["eat...
    刻苦驴哝阅读 134评论 0 0
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 7,752评论 16 22
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    余生动听阅读 10,751评论 0 11

友情链接更多精彩内容