题目:同字符分组

难度:Medium

题目内容

Given an array of strings, group anagrams together.

翻译:给定一组字符串数组,按相同字符组成的字符串分为一组。

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

我的思路:因为要分组,那么使用map即可,相同的字符作为键,值为一个List作为对应分组

1、首先遍历,每次将当前字符串打断成char数组,然后sort,判断map中是否包含此sort后的char

2、是的话则将此字符串add进此key对应的值(List)里面

  否则往map里put一个新的键值对

我的代码:

     public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) return new ArrayList<List<String>>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String s : strs) {
char[] ca = s.toCharArray();
Arrays.sort(ca);
String keyStr = String.valueOf(ca);
if (!map.containsKey(keyStr)) map.put(keyStr, new ArrayList<String>());
map.get(keyStr).add(s);
}
return new ArrayList<List<String>>(map.values());
}

我的复杂度:O(N*K*logK)  ———k为最长的字符串长度,sort方法为klogk

编码过程中的问题

1、一开始使用的键为char[],后来发现数组的equals方法使用的是最原始的比较地址,并不会比较其中的内容,所以改成了String就好了;

2、将map转为List只需要调用map.values()方法就会返回一个包含所有元素的Collection,然后用其子类的构造方法接住都行。

答案代码

     public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0) return new ArrayList();
Map<String, List> ans = new HashMap<String, List>();
int[] count = new int[26];
for (String s : strs) {
Arrays.fill(count, 0);
for (char c : s.toCharArray()) count[c - 'a']++; StringBuilder sb = new StringBuilder("");
for (int i = 0; i < 26; i++) {
sb.append(count[i]);
}
String key = sb.toString();
if (!ans.containsKey(key)) ans.put(key, new ArrayList());
ans.get(key).add(s);
}
return new ArrayList(ans.values());
}

答案复杂度:O(N*K)

答案思路

1、和我的方法一样对String数组进行循环;

2、然后没有使用排序,而是做了一个只包含26个元素的数组,直接记录26个字母各有多少个

3、将这26个int,按顺序取出并拼接成一个字符串,这样也能表示使用相同字母的字符串的key

4、map没有则用此key,put一个List(有则不需要操作)。然后对应key的List直接add进当前String。

LeetCode第[49]题(Java):Group Anagrams的更多相关文章

  1. 【LeetCode每天一题】Group Anagrams(变位词组)

    Given an array of strings, group anagrams together. Example: Input: ["eat", "tea" ...

  2. LeetCode第[18]题(Java):4Sum 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...

  3. LeetCode第[1]题(Java):Two Sum 标签:Array

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  4. LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2

    题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...

  5. LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  6. 【Leetcode】【Medium】Group Anagrams

    Given an array of strings, group anagrams together. For example, given: ["eat", "tea& ...

  7. LeetCode第[11]题(Java):Container With Most Water 标签:Array

    题目难度:Medium Given n non-negative integers a1, a2, ..., an, where each represents a point at coordina ...

  8. LeetCode第[4]题(Java):Median of Two Sorted Arrays 标签:Array

    题目难度:hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median ...

  9. LeetCode第[29]题(Java):Divide Two Integers

    题目:两整数相除 难度:Medium 题目内容: Given two integers dividend and divisor, divide two integers without using ...

随机推荐

  1. MVC异步消息推送机制

    在MVC里面,有异步控制器,可以实现模拟消息推送机制功能 1.控制器要继承至AsyncController,如 public class RealTimeController : AsyncContr ...

  2. https://github.com/arut/nginx-rtmp-module.git

    https://github.com/arut/nginx-rtmp-module.git NGINX-based Media Streaming Server nginx-rtmp-module P ...

  3. 模块 - random/string/os/sys/shutil/zipfile/tarfile

    random 模块 方法: >>> random.randint(1,3) #会包含 1 2 3 3 >>> random.randrange(1,3) #会包含 ...

  4. BaseDao 接口

    // 以后所有的 Dao 接口都需要继承 BaseDao 接口; // 自定义泛型接口 public interface BaseDao<T>{ public void save(T t) ...

  5. ubuntu14 编译安装(升级)g++

    编译安装(升级)g++ ubuntu14自带的g++为4.8.4,不支持c++11.现要将g++升至5.2.0 1.下载安装: 参考https://www.cppfans.org/1719.html ...

  6. windows下使用IIS创建git服务

    Bonobo Git Server 下载地址: https://bonobogitserver.com/ 安装方法:https://bonobogitserver.com/install/ 配置简单, ...

  7. node.js---sails项目开发(6)--- 实现分页功能

    只需要添加一个文件即可  api/blueprints/find.js     代码如下 /** * Module dependencies */ var util = require('util') ...

  8. C# 事件浅析

    前言 对于搞.net的朋友来说,经常会遇到关于事件和委托的问题:事件与委托有什么关系?事件的本质是什么?委托的本质又是什么?由于.net 做了大量的封装,对于初学者,这两个概念确实不怎么好理解.事件是 ...

  9. MySQL之存储引擎(Day39)

    一 什么是存储引擎 mysql中建立的库=====>文件夹 库中建立的表=====>文件 现实生活中我们用来存储数据的文件应该有不同的类型:比如存文本用txt类型,存表格用excel,存图 ...

  10. django生成json

    好方便啊……list什么的一下都变成json了呢! import json from django.core.serializers.json import DjangoJSONEncoder def ...