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.
  • 相关阅读:
    源文件声明规则
    JavaBean
    ffmpeg错误:Invalid UE golomb code
    利用android studio 生成 JNI需要的动态库so文件
    Error: Your project contains C++ files but it is not using a supported native build system.
    Andriod studio 目录结构
    ubuntu 16.04扩充root 分区
    错误: H.264 bitstream malformed, no startcode found,
    CIDR
    Qt之QComboBox定制(二)
  • 原文地址:https://www.cnblogs.com/null00/p/5077662.html
Copyright © 2011-2022 走看看