1.题目描述2.解题思路及代码
1.题目描述给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 字母异位词 是由重新排列源单词的字母得到的一个新单词,所有源单词中的字母通常恰好只用一次。 Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] Input: strs = [""] Output: [[""]] Input: strs = ["a"] Output: [["a"]]2.解题思路及代码
方法一:哈希表
思路:确定使用的数据结构,由返回值可知,使用Map
具体代码如下:
public static List> groupAnagrams(String[] strs) { //判断是否为空字符串数组 if(strs == null || strs.length == 0){ return new ArrayList(); } //1.创建一个哈希表 Map
map = new HashMap (); for (String s: strs) { //将字符串转化为字符数组 char[] chars = s.toCharArray(); //对字符数组按照字母顺序排序 Arrays.sort(chars); //将排序后的字符串作为哈希表中的key值 String key = String.valueOf(chars); //2.判读哈希表中是否有该key值 if (!map.containsKey(key)){ //若不存在,则为新的异位词语,在map中创建新的键值对 map.put(key,new ArrayList()); } //3.将该字符串放在对应key的list中 map.get(key).add(s); } //返回map中所有键值对象构成的list return new ArrayList(map.values()); }
时间复杂度:O(nlogn),因为使用到了排序
空间复杂度:O(logn),因为使用到了排序
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/group-anagrams



