• Leetcode——————Group Anagrams


    这道题对我来说比较难:

    1.首先题目要求输出的结果,应该用什么形式的数据结构来存储呢

    2.涉及到map,collection,sort( )等函数,或者其他的一堆东西,几乎一无所知。

    copy大神代码如下:

    public class Solution {

    //返回值是以链表作为节点的链表。
     public List<List<String>> groupAnagrams(String[] strs) {
     Map<String, List<String>> map = new HashMap<String, List<String>>();

     for(String str : strs){
     // 将单词按字母排序
     char[] carr = str.toCharArray();
    Arrays.sort(carr);按某种作者要求的顺序来排序!
     String key = new String(carr);
     //得到的是键的存放位置
     List<String> list = map.get(key);返回值到底是什么,不太理解。
     if(list == null){
     list = new ArrayList<String>();
    }
    list.add(str);
     map.put(key, list);
    }

     List<List<String>> res = new ArrayList<List<String>>();
     // 将列表按单词排序
     for(String key : map.keySet()){
     List<String> curr = map.get(key);
    Collections.sort(curr);
    res.add(curr);
    }
     return res;
    }
    }

    //运行后居然超时,另选代码如下:

    public class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            if (strs == null) {
                return null;
            }
            HashMap<String, List<String>> hm = new HashMap<>();
            for (int i = 0; i < strs.length; i++) {
                char[] c = strs[i].toCharArray();
                Arrays.sort(c);
                String str = new String(c);
                if (hm.containsKey(str)) {
                    hm.get(str).add(strs[i]);
                } else {
                    List<String> ana = new ArrayList<>();
                    ana.add(strs[i]);
                    hm.put(str, ana);
                }
            }
            return new ArrayList<List<String>>(hm.values());
        }
    }

  • 相关阅读:
    word上怎么打钩
    POI操作excel常用方法总结
    web.xml中Filter过滤器标签说明
    IDEA使用操作说明(自己总结)
    windows 64位上oracle 11g安装
    List<T>与List<?>的区别
    java分页之假分页
    CDN之Web Cache
    HTTP之缓存技术
    HTTP之Cookie和Session
  • 原文地址:https://www.cnblogs.com/maowuyu-xb/p/6754069.html
Copyright © 2020-2023  润新知