本文主要是介绍leetcode 49. Group Anagrams(哈希,字典序),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目大意:把一个字符串数组按字母组成的不同分到几个字符串数组,把每个字符串数组按字典序排序
解题方法:先用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 49. Group Anagrams(哈希,字典序)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!