49. Group Anagrams

栏目: Java · 发布时间: 5年前

内容简介:Given an array of strings, group anagrams together.Example:Note:

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.

难度:medium

题目:给定一个字符串数组,将 颠倒字母而成的单词 组合在一起。

注意:所有输入都为小写字母

思路:都按字母序排序。

Runtime: 14 ms, faster than 85.30% of Java online submissions for Group Anagrams.

Memory Usage: 34.1 MB, less than 16.58% of Java online submissions for Group Anagrams.

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> msl = new HashMap<>();
        
        for (int i = 0; i < strs.length; i++) {
            char[] sc = strs[i].toCharArray();
            Arrays.sort(sc);
            String ns = new String(sc);
            msl.putIfAbsent(ns, new ArrayList<String>());
            msl.get(ns).add(strs[i]);
        }
        
        return new ArrayList(msl.values());
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Head First 设计模式(中文版)

Head First 设计模式(中文版)

弗里曼 / O'Reilly Taiwan公司 / 中国电力出版社 / 2007-9 / 98.00元

《Head First设计模式》(中文版)共有14章,每章都介绍了几个设计模式,完整地涵盖了四人组版本全部23个设计模式。前言先介绍这本书的用法;第1章到第11章陆续介绍的设计模式为Strategy、Observer、Decorator、Abstract Factory、Factory Method、Singleton,Command、Adapter、Facade、TemplateMethod、I......一起来看看 《Head First 设计模式(中文版)》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器