您的位置:首页 > 其它

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

2016-12-26 09:27 543 查看
题目大意:把一个字符串数组按字母组成的不同分到几个字符串数组,把每个字符串数组按字典序排序
解题方法:先用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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: