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

Group Anagrams

时间:2018-03-13 13:58:44      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:group   value   lis   char   gpo   put   ams   eth   amp   

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]
public List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<String>> map = new HashMap<>();
        for (String string:strs){
            char[] chars = string.toCharArray();
            Arrays.sort(chars);
            String value = String.valueOf(chars);
            if (!map.containsKey(value)){
                List<String> list = new ArrayList<>();
                map.put(value,list);
            }
            map.get(value).add(string);
        }
        List<List<String>> lists = new ArrayList<>();
        for (List<String> list:map.values()) {
            lists.add(list);
        }
        return lists;
    }

Group Anagrams

标签:group   value   lis   char   gpo   put   ams   eth   amp   

原文地址:https://www.cnblogs.com/bingo2-here/p/8555961.html

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