• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Group Anagrams

 
Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Note:

All inputs will be in lowercase.
The order of your output does not matter.

 

if want lexicographic order,然后要用Collections.sort() 来保证字典序

for (List<String> each : map.values()) {
  Collections.sort(each);
  res.add(new ArrayList<String>(each));
}

 

 1 class Solution {
 2     public List<List<String>> groupAnagrams(String[] strs) {
 3         List<List<String>> res = new ArrayList<>();
 4         HashMap<String, List<String>> map = new HashMap<>();
 5         
 6         for (String str : strs) {
 7             char[] arr = str.toCharArray();
 8             Arrays.sort(arr);
 9             String sorted = Arrays.toString(arr);
10             // if (!map.containsKey(sorted)) map.put(sorted, new ArrayList<String>());
11             map.putIfAbsent(sorted, new ArrayList<String>());
12             map.get(sorted).add(str);
13         }
14         
15         for (List<String> value : map.values()) {
16             res.add(value);
17         }
18         return res;
19     }
20 }

 

 

 

posted @ 2014-06-26 08:10  neverlandly  阅读(393)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3