zoukankan      html  css  js  c++  java
  • 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());
        }
    }

  • 相关阅读:
    systemctld 启动理解
    公私钥(证书)理解
    布隆过滤器
    python linux下dbg
    iOS基础尺寸图
    metadataObjectTypes 详解
    pkg_config_path 环境变量设置 教程
    Cloning failed using an ssh key for authentication, enter your GitHub credentials to access private 解决方案
    docker php安装GD扩展
    mysql 隔离级别
  • 原文地址:https://www.cnblogs.com/maowuyu-xb/p/6754069.html
Copyright © 2011-2022 走看看