码迷,mamicode.com
首页 > 编程语言 > 详细

49.Submission Details java solutions

时间:2016-06-30 12:25:21      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!