码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Group Anagrams

时间:2016-09-03 06:22:47      阅读: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.
public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if(strs==null || strs.length==0){
            return null;
        }
        List<List<String>> resList=new ArrayList<List<String>>();
        Map<String, List<String>> map=new HashMap<String, List<String>>();
        for(int i=0; i<strs.length; i++){
            String str=strs[i];
            char[] chars=str.toCharArray();
            Arrays.sort(chars);
            String key=new String(chars);
            if(map.containsKey(key)){
                List<String> strList=map.get(key);
                strList.add(str);
                map.put(key,strList);
            }
            else{
                List<String> strList=new ArrayList<String>();
                strList.add(str);
                map.put(key, strList);
            }
        }
        for(String key : map.keySet()){
            resList.add(map.get(key));
        }
        return resList;
    }
}

 

LeetCode-Group Anagrams

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5836129.html

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