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

49. Group Anagrams

时间:2016-06-11 07:08:02      阅读:329      评论: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) {
        Map<String, List<String>> map = new HashMap<>();
        
        for(String s : strs)
        {
            char[] key = s.toCharArray();
            Arrays.sort(key);
            String sKey = new String(key);
            List<String> dest = map.get(sKey);
            if(dest == null)
            {
                dest = new ArrayList<String>();
                map.put(sKey, dest);
            }
            dest.add(s);
        }
        
        List<List<String>> ret = new ArrayList<>();
        for(List<String> group: map.values())
        {
            ret.add(group);
        }
        return ret;
    }
}

 

49. Group Anagrams

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/5574653.html

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