• Leetcode: Group Anagrams


     
    Given an array of strings, group anagrams together.
    
    Example:
    
    Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
    Output:
    [
      ["ate","eat","tea"],
      ["nat","tan"],
      ["bat"]
    ]
    Note:
    
    All inputs will be in lowercase.
    The order of your output does not matter.

    if want lexicographic order,然后要用Collections.sort() 来保证字典序

    for (List<String> each : map.values()) {
      Collections.sort(each);
      res.add(new ArrayList<String>(each));
    }

     1 class Solution {
     2     public List<List<String>> groupAnagrams(String[] strs) {
     3         List<List<String>> res = new ArrayList<>();
     4         HashMap<String, List<String>> map = new HashMap<>();
     5         
     6         for (String str : strs) {
     7             char[] arr = str.toCharArray();
     8             Arrays.sort(arr);
     9             String sorted = Arrays.toString(arr);
    10             // if (!map.containsKey(sorted)) map.put(sorted, new ArrayList<String>());
    11             map.putIfAbsent(sorted, new ArrayList<String>());
    12             map.get(sorted).add(str);
    13         }
    14         
    15         for (List<String> value : map.values()) {
    16             res.add(value);
    17         }
    18         return res;
    19     }
    20 }
  • 相关阅读:
    Oracle数据库5--数据库对象
    Oracle数据库4--多表关联
    Session
    cookie
    Servlet的部分response响应处理
    Servlet的部分request请求处理
    Linux部分命令
    Linux基础
    弹性布局
    animation 动画
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3809312.html
Copyright © 2020-2023  润新知