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

*Group Anagrams

时间:2016-01-02 14:20:37      阅读:230      评论: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:

  1. For the return value, each inner list‘s elements must follow the lexicographic order.
  2. All inputs will be in lower-case.

 

public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs == null || strs.length == 0) return new ArrayList<List<String>>();
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        Arrays.sort(strs);
        for (String s : strs) {
            char[] ca = s.toCharArray();
            Arrays.sort(ca);
            String keyStr = String.valueOf(ca);
            if (!map.containsKey(keyStr)) map.put(keyStr, new ArrayList<String>());
            map.get(keyStr).add(s);
        }
        return new ArrayList<List<String>>(map.values());
    }
}

reference:https://leetcode.com/discuss/58561/share-my-short-java-solution

 

*Group Anagrams

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5094451.html

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