2015年9月22日星期二

Leetcode 49 Group Anagrams

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.

Solution 1: Use HashMap
 public class Solution {  
   public List<List<String>> groupAnagrams(String[] strs) {  
     Arrays.sort(strs);  
     Map<String,List<String>> map=new HashMap<>();  
     for (String s: strs) {  
       String key=format(s);  
       if (map.containsKey(key)) map.get(key).add(s);  
       else {  
         List<String> one=new ArrayList<>();  
         one.add(s);  
         map.put(key,one);  
       }  
     }  
     List<List<String>> res=new ArrayList<>();  
     for (List<String> one: map.values()) res.add(one);  
     return res;  
   }  
   private String format(String s) {  
     char[] c=s.toCharArray();  
     Arrays.sort(c);  
     return new String(c);  
   }  
 }  

没有评论:

发表评论