leetcode 49. Group Anagrams(哈希,字典序)

来源:互联网 发布:阿里云上海机房地址 编辑:程序博客网 时间:2024/05/22 18:57
题目大意:把一个字符串数组按字母组成的不同分到几个字符串数组,把每个字符串数组按字典序排序
解题方法:先用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();}}}


0 0