49 字母异位词分组

84 阅读1分钟

一.自我分析

做这道题的时候,第一个想到的是之前做过异位词的的滑动窗口问题,现在这道题主要用的方法并不是这个,是hashmap,我想到的是拿乘积和当作key值,但是还是会造成重复,不能ac,只能达到90%的通过率✅

我的解法:

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        int n = strs.length;
        List<List<String>> ans = new ArrayList<>();
        Map<Long, List<String>> map = new HashMap<>();
        for(String s : strs) {
            long num = 0;
            for(int i = 0;i < s.length();i ++) {
                num += s.charAt(i) * s.charAt(i);
            }
            if(map.getOrDefault(num , null) != null) {
                List<String> now = map.get(num);
                now.add(s);
                map.put(num, now);
            } else {
                List<String> now = new ArrayList<>();
                now.add(s);
                map.put(num, now);
            }
        }
        for(Map.Entry<Long, List<String>> entry : map.entrySet()) {
            ans.add(entry.getValue());
        }
        return ans;
    }
}

二.AC解法

官方给的题解一个就是排序,把异位词的字母顺序重新排序,然后作为string当作key值,存到hashmap里面,这样就会解决加起来数值重复的问题了

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
      int n = strs.length;
      Map<String, List<String>> ans = new HashMap<>();
      for(String s : strs) {
        char[] sc = s.toCharArray();
        Arrays.sort(sc);  // 这块地方是关键
        List<String> now = ans.getOrDefault(new String(sc), new ArrayList<>());
        now.add(s);
        ans.put(new String(sc), now);
      }
      return new ArrayList<List<String>>(ans.values());
  }
}