• 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 }
  • 相关阅读:
    牛客算法周周练2
    牛客算法周周练2
    2020年7月7日Java学习日记
    2020年7月6日Java学习日记
    练习29--if语句
    练习28--布尔练习
    练习27--记忆逻辑
    第18~19讲课后作业
    第20讲:内嵌函数和闭包
    练习25--更多更多练习
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3809312.html
Copyright © 2020-2023  润新知