2015年11月4日星期三

Leetcode 249 Group Shifted Strings

Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Return:
[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]
Note: For the return value, each inner list's elements must follow the lexicographic order.
Solution 1: Use the one start with 'a' as the key.
 public class Solution {  
   public List<List<String>> groupStrings(String[] strings) {  
     Map<String,List<String>> map=new HashMap<>();  
     for (String s: strings) {  
       String key=genKey(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> l:map.values()) {  
       Collections.sort(l);  
       res.add(l);  
     }  
     return res;  
   }  
   private String genKey(String s) {  
     if (s.length()==0) return "";  
     char[] c=s.toCharArray();  
     int offset=c[0]-'a';  
     for (int i=0; i<c.length; i++) {  
       c[i]-=offset;  
       if (c[i]<'a') c[i]+=26;  
     }  
     return new String(c);  
   }  
 }  

没有评论:

发表评论