1,问题描述
49. 字母异位词分组
难度:中等
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:
1 2
| 输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"] 输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
|
示例 2:
1 2
| 输入: strs = [""] 输出: [[""]]
|
示例 3:
1 2
| 输入: strs = ["a"] 输出: [["a"]]
|
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i]
仅包含小写字母
2,初步思考
直接想到了针对字符串升序重排列作为key,value为原始顺序的字符串,最后在一起整理
3,代码处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import java.util.*;
public class _49字母异位词分组 {
public List<List<String>> groupAnagrams_v2(String[] strs) { Map<String, List<String>> map = new HashMap<>(); for (String str : strs) { String key = getKey(str); if (map.containsKey(key)) { map.get(key).add(str); } else { List<String> strings = new ArrayList<>(); strings.add(str); map.put(key, strings); } } return new ArrayList<>(map.values()); }
private String getKey(String str) { int[] count = new int[26]; char[] charArray = str.toCharArray(); for (int i = 0; i < charArray.length; i++) { count[charArray[i] - 'a']++; }
StringBuilder sb = new StringBuilder(); for (int i = 0; i < count.length; i++) { if (count[i] != 0) { sb.append((char) ('a' + i)); sb.append(count[i]); } } return sb.toString(); }
public List<List<String>> groupAnagrams_sort(String[] strs) { Map<String, List<String>> map = new HashMap<>(); for (String str : strs) { char[] charArray = str.toCharArray(); Arrays.sort(charArray); String key = String.valueOf(charArray); if (map.containsKey(key)) { map.get(key).add(str); } else { List<String> strings = new ArrayList<>(); strings.add(str); map.put(key, strings); } } return new ArrayList<>(map.values()); }
public static void main(String[] args) { _49字母异位词分组 groupAnagrams = new _49字母异位词分组(); System.out.println(groupAnagrams.groupAnagrams_v2(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"})); } }
|