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

[?]*Group Shifted Strings

时间:2015-12-25 07:40:19      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:

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"]
]


 1  public class Solution {
 2     public List<List<String>> groupStrings(String[] strings) {
 3 
 4         List<List<String>> res = new ArrayList<List<String>>();
 5         HashMap<String, List<String>> map = new HashMap<String, List<String>>();
 6 
 7         for(String word : strings){
 8             String key = "";
 9             int offset = word.charAt(0) - ‘a‘;
10             for(int i = 1; i < word.length(); i++){
11                 key += (word.charAt(i) - offset + 26) % 26;
12             }
13 
14             if(!map.containsKey(key)){
15                 map.put(key, new ArrayList<String>());
16             }
17             map.get(key).add(word);
18         }
19 
20         for(List<String> list : map.values()){
21             Collections.sort(list);
22             res.add(list);
23         }
24 
25         return res;
26 
27     }
28 }

reference: https://leetcode.com/discuss/67240/around-13-lines-code-in-java

[?]*Group Shifted Strings

标签:

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

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