题目:同字符分组

难度: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. android 反汇编一些资料

    Android软件安全与逆向分析   http://book.2cto.com/201212/12432.html Smali--Dalvik虚拟机指令语言 http://blog.csdn.net/ ...

  2. js 中和c类似

    w <script type="text/javascript"> <!-- var w = 123 alert(w) function fun(){ alert ...

  3. JQuery设置checkbox选中或取消等相关操作

    $("[name='checkbox']").attr("checked",'true');//全选 $("[name='checkbox']&quo ...

  4. Qt 如何自动安装常用依赖?

    使用 *.prf 文件自动安装依赖 在 Qt\Qt5.9.5\5.9.5\msvc2015\mkspecs\features 路径中添加 auto_install.prf 文件 然后在程序配置文件(* ...

  5. 我的Android进阶之旅------>解决:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.

    错误描述 今天在Android Studio项目中加入了jackson的开发包,编译运行时候,引发了如下的错误: Error:Execution failed for task ':app:trans ...

  6. Leetcode 之 Valid Triangle Number

    611. Valid Triangle Number 1.Problem Given an array consists of non-negative integers, your task is ...

  7. mysql进阶(二)之细谈索引、分页与慢日志

    索引 1.数据库索引 数据库索引是一种数据结构,可以以额外的写入和存储空间为代价来提高数据库表上的数据检索操作的速度,以维护索引数据结构.索引用于快速定位数据,而无需在每次访问数据库表时搜索数据库表中 ...

  8. tornado下使用静态文件和文件缓存

    静态文件和文件缓存 1.在应用配置 settings 中指定 static_path 选项来提供静态文件服务:   2.在应用配置 settings 中指定 static_url_prefix 选项来 ...

  9. ajax异步请求返回对象

    使用ajax异步请求返回一个对象. java code: @RequestMapping({"getAstSingleWheelImg_bbs"+Constant.JSON}) @ ...

  10. day11 函数和命名空间

    # def my_sum(*args):# sum_2=0# for i in args:# sum_2+=i# return sum_2### ret=my_sum(1,2,3,4)# print( ...