标签:
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case.
题意就是对同构词进行分类,存到list之后再返回。
1 public class Solution { 2 public List<List<String>> groupAnagrams(String[] strs) { 3 Map<String,ArrayList<String>> map = new HashMap<String,ArrayList<String>>(); 4 for(String str : strs){ 5 String tmp = sortStr(str); 6 if(map.containsKey(tmp)){ 7 map.get(tmp).add(str); 8 }else{ 9 ArrayList<String> list = new ArrayList<String>(); 10 list.add(str); 11 map.put(tmp,list); 12 } 13 } 14 List<List<String>> ans = new ArrayList<List<String>>(map.values()); 15 // for(List<String> a : ans){ 16 // Collections.sort(a); 17 // } 18 return ans; 19 } 20 21 public String sortStr(String str){ 22 char[] tmp = str.toCharArray(); 23 Arrays.sort(tmp); 24 return new String(tmp); 25 } 26 }
49.Submission Details java solutions
标签:
原文地址:http://www.cnblogs.com/guoguolan/p/5629443.html