leetcode 49. Group Anagrams(哈希,字典序)
2016-12-26 09:27
543 查看
题目大意:把一个字符串数组按字母组成的不同分到几个字符串数组,把每个字符串数组按字典序排序
解题方法:先用HashMap类对字符串数组哈希,再把每个字符串数组进行字典序排序
要 点:
HashMap类的使用
Arrays.sort(chars); 一个char[]的字典序排序
Collections.sort(res); 一个字符串数组的字典序排序
解题方法:先用HashMap类对字符串数组哈希,再把每个字符串数组进行字典序排序
要 点:
HashMap类的使用
Arrays.sort(chars); 一个char[]的字典序排序
Collections.sort(res); 一个字符串数组的字典序排序
package leetcode49HashSort; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; class Solution{ public List<List<String>> groupAnagrams(String[] strs) { int i; List<List<String>> result = new ArrayList<>(); if(strs == null || strs.length == 0) return result; HashMap<String,List<String>> map = new HashMap<>(); for(i=0;i<strs.length;i++) { char[] chars=strs[i].toCharArray(); Arrays.sort(chars); String temp = new String(chars); if(!map.containsKey(temp)) { List<String> singleResultList = new ArrayList<>(); singleResultList.add(strs[i]); map.put(temp, singleResultList); } else { map.get(temp).add(strs[i]); } } /* Iterator<Map.Entry<String,List<String>>>iterator = map.entrySet().iterator(); while(iterator.hasNext()) { Map.Entry<String, List<String>> entry = iterator.next(); List<String> temp_list = entry.getValue(); Collections.sort(temp_list); result.add(temp_list); } */ result = new ArrayList<List<String>>(map.values()); for(List<String> res : result) { Collections.sort(res); } return result; } } public class hello { public static void main(String args[]) { int i,j; String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"}; Solution mySolution = new Solution(); List<List<String>> result= mySolution.groupAnagrams(strs); for(i=0;i<result.size();i++) { List<String> thisList=new ArrayList<>(); thisList = result.get(i); for(j=0;j<thisList.size();j++) System.out.print(thisList.get(j)+" "); System.out.println(); } } }
相关文章推荐
- LeetCode-1-Two Sum(哈希)-Medium
- leetcode_202题——Happy Number(哈希)
- LeetCode 3. Longest Substring Without Repeating Characters(线性处理, 哈希)
- leetcode_c++:哈希:intersection of Two Arrays(349)
- leetCode 202. Happy Number 哈希
- leetcode_c++:哈希: Copy List with Random Pointer(138)
- leetcode_c++:哈希:Intersection of Two Arrays II(350)
- LeetCode Next Permutation(字典序排列)
- LeetCode_HappyNumber_哈希表的使用
- [LeetCode386]Lexicographical Numbers(n以内的数字按字典序输出)
- leetCode 350. Intersection of Two Arrays II 哈希
- Next Permutation -- LeetCode(下一个字典序)
- leetcode 哈希表专题-Word Pattern
- leetcode_c++:哈希:Max Points on a Line(149)
- LeetCode 217. Contains Duplicate 哈希
- LeetCode Isomorphic Strings 哈希
- leetcode_c++:哈希:word pattern(290)
- leetcode--two-sum--哈希
- [leetcode]two sum (遍历 哈希)
- leetcode_c++:哈希:Longest Substring Without Repeating Characters(003)