算法 -- 字母异位词分组

2022-07-27,,,

LeetCode刷题记71

49. 字母异位分组

题目

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> ans = new ArrayList();
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (int i = 0; i < strs.length; i ++) {
            int[] nums = new int[26];
            for (int j = 0; j < strs[i].length(); j ++) {
                nums[strs[i].charAt(j) - 'a'] ++;
            }
            String s = "";
            for (int j = 0; j < 26; j ++) {
                s += nums[j] + ".";
            }
            System.out.println(s);
            if (map.containsKey(s)) {
                List<String> tmp = map.get(s);
                tmp.add(strs[i]);
                map.put(s, tmp);
            } else {
                List<String> tmp = new ArrayList<String>();
                tmp.add(strs[i]);
                map.put(s, tmp);
            }
        }
        for (List<String> list : map.values()) {
            ans.add(list);
        }
        return ans;
    }
}

关键是找一个hash算法将字符串映射
3/5
71/150

本文地址:https://blog.csdn.net/weixin_44013557/article/details/110259342

《算法 -- 字母异位词分组.doc》

下载本文的Word格式文档,以方便收藏与打印。