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.
class Solution { public List<List<String>> groupAnagrams(String[] strs) { // if (strs.length == 0) return new ArrayList(); // Map<String, List> ans = new HashMap<String, List>(); // for (String s : strs) { // char[] ca = s.toCharArray(); // Arrays.sort(ca); // String key = String.valueOf(ca); // if (!ans.containsKey(key)) ans.put(key, new ArrayList()); // ans.get(key).add(s); // } // return new ArrayList(ans.values()); if(strs.length == 0) return new ArrayList(); Map<String, List> ans = new HashMap<String, List>(); for(String s : strs){ char[] ca = s.toCharArray(); Arrays.sort(ca); String key = String.valueOf(ca); if(!ans.containsKey(key)) ans.put(key, new ArrayList()); ans.get(key).add(s); } return new ArrayList(ans.values()); } }
String to chararrya: S.toCharArray()
Sort charArray c: Arrays.sort(c)
charArray to String: String.valueOf(c)
get all values of a hashset: ans.values()
-
能想到类似的方法,但是脑子里面的API不够实现,所以之后多记一些API。
另:
再来看一种方法,不用sort,用一个长度为26的int数组来存放各char出现的次数,不过一顿操作0-5,本质上还是一种又臭又长的方法
class Solution { 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('#'); 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()); } }