zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    Given an array of strings, group anagrams together.

    For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
    Return:

    [
      ["ate", "eat","tea"],
      ["nat","tan"],
      ["bat"]
    ]

    Note:

        For the return value, each inner list's elements must follow the lexicographic order.
        All inputs will be in lower-case.

    思路:

    HashMap, 对每个字符串所包含的字符进行排序,得到一个key,value为响应的list。

    package anagram;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.List;
    
    public class GroupAnagrams {
    
        public List<List<String>> groupAnagrams(String[] strs) {
            HashMap<String, List<String>> map = new HashMap<String, List<String>>();
            for (int i = 0; i < strs.length; ++i) {
                char[] chars = strs[i].toCharArray();
                Arrays.sort(chars);
                String key = String.valueOf(chars);
                if (map.containsKey(key)) {
                    map.get(key).add(strs[i]);
                } else {
                    List<String> list = new ArrayList<String>();
                    list.add(strs[i]);
                    map.put(key, list);
                }
            }
            List<List<String>> res = new ArrayList<List<String>>();
            for (List<String> l : map.values()) {
                Collections.sort(l);
                res.add(l);
            }
            
            return res;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            String[] strs = { "eat", "tea", "tan", "ate", "nat", "bat" };
            GroupAnagrams g = new GroupAnagrams();
            List<List<String>> res = g.groupAnagrams(strs);
            for (List<String> subRes : res) {
                for (String s : subRes)
                    System.out.print(s + "	");
                System.out.println("
    ");
            }
        }
    
    }

    Given an array of strings, group anagrams together.

    For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
    Return:

    [
      ["ate", "eat","tea"],
      ["nat","tan"],
      ["bat"]
    ]

    Note:

    1. For the return value, each inner list's elements must follow the lexicographic order.
    2. All inputs will be in lower-case.
  • 相关阅读:
    Alice and Bob 要用到辗转相减
    Java经典设计模式
    设计模式---创建类---建造者模式
    luogu4267 TamingtheHerd (dp)
    nowcoder172C 保护 (倍增lca+dfs序+主席树)
    nowcoder172A 中位数 (二分答案)
    bzoj4985 评分 (二分答案+dp)
    luogu4269 Snow Boots G (并查集)
    luogu4268 Directory Traversal (dfs)
    bzoj1001/luogu4001 狼抓兔子 (最小割/平面图最小割转对偶图最短路)
  • 原文地址:https://www.cnblogs.com/null00/p/5077662.html
Copyright © 2011-2022 走看看