leetcode49 - Group Anagrams - medium
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.
Map与序列化。O(n*L), n为字符串个数,L为字符串长度
1.让所有的anagram有一个共同的签名,从而让他们能因为这个共性被map聚集到一起。
2.产生签名的方法:a) 给字符串内的字符排序 b)统计各a-z出现频次并把频次拼接到一起。采用b更好,签名长度稳定在26单位左右。
实现:
class Solution { public List<List<String>> groupAnagrams(String[] strs) { List<List<String>> ans = new ArrayList<>(); if (strs == null || strs.length == 0) { return ans; } Map<String, List<String>> map = new HashMap<>(); for (String s : strs) { String sig = signature(s); map.putIfAbsent(sig, new ArrayList<String>()); map.get(sig).add(s); } for (List<String> list : map.values()) { ans.add(list); } return ans; } private String signature(String s) { int[] cnt = new int[26]; for (char c : s.toCharArray()) { cnt[c - 'a']++; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < cnt.length; i++) { sb.append(cnt[i]).append('#'); } return sb.toString(); } }