zoukankan      html  css  js  c++  java
  • 程序员面试金典-面试题 10.02. 变位词组

    题目:

    编写一种方法,对字符串数组进行排序,将所有变位词组合在一起。变位词是指字母相同,但排列不同的字符串。

    注意:本题相对原题稍作修改

    示例:

    输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
    输出:
    [
    ["ate","eat","tea"],
    ["nat","tan"],
    ["bat"]
    ]
    说明:

    所有输入均为小写字母。
    不考虑答案输出的顺序。

    分析:

    统计每个字符串字符出现的频次,并按照a-z的顺序拼接起来,利用这个当做区分变为单词依据,并当做HashMap中的key,并将字符串加入key对应的list中。最后将list整合到结果中。

    程序:

    class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            List<List<String>> res = new ArrayList<>();
            map = new HashMap<>();
            for(String str:strs){
                int[] dict = new int[26];
                for(char ch:str.toCharArray()){
                    dict[ch - 'a']++;
                }
                StringBuilder s = new StringBuilder();
                for(int i = 0; i < 26; ++i){
                    while(dict[i]-- > 0){
                        s.append(i + 'a');
                    }
                }
                List<String> list = map.getOrDefault(s.toString(), new ArrayList<>());
                list.add(str);
                map.put(s.toString(), list);
            }
            for(List<String> l:map.values())
                res.add(l);
            return res;
        }
        private HashMap<String, List<String>> map;
    }
  • 相关阅读:
    docker在Linux环境下的安装
    docker在Windows环境下的安装
    tcpdump和windump
    Centos7下安装Elasticsearch 5.6.6
    使用concurrent.futures模块并发,实现进程池、线程池
    Nginx配置Gzip
    linux常用命令
    Linux下文档与目录结构
    快速读取大文件的几种方式
    linux 将大文件分解为多个小文件
  • 原文地址:https://www.cnblogs.com/silentteller/p/12470709.html
Copyright © 2011-2022 走看看