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

Leetcode: 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.

关键点:group all strings that belong to the same shifting sequence, 所以找到属于相同移位序列的key 很重要。因此单独写了函数shift,

写这个shift函数,我之前想的很复杂,每个String要移26个距离,看shifted string是不是一个key。其实干嘛这么复杂,指定一个相同移位序列的key,定义为第一个char为‘a’

buffer.append((c - 'a' - dist + 26) % 26 + 'a') 极容易错。将相同移位序列的Strings存入key 对应的value中,建立正确的HashMap很重要。

 1 public class Solution {
 2     public List<List<String>> groupStrings(String[] strings) {
 3         List<List<String>> res = new ArrayList<List<String>>();
 4         if (strings==null || strings.length==0) return res;
 5         HashMap<String, List<String>> map = new HashMap<String, List<String>>();
 6         for (int i=0; i<strings.length; i++) {
 7             String temp = shift(strings[i]);
 8             if (map.containsKey(temp)) {
 9                 map.get(temp).add(strings[i]);
10             }
11             
12             else {
13                 List<String> li= new ArrayList<String>();
14                 li.add(strings[i]);
15                 map.put(temp, li);
16             }
17             
18         }
19         for (List<String> each : map.values()) {
20             Collections.sort(each);
21             res.add(new ArrayList<String>(each));
22         }
23         return res;
24     }
25     
26     public String shift(String cur) {
27         StringBuffer res = new StringBuffer();
28         int len = cur.length();
29         int dist = cur.charAt(0) - 'a';
30         for (int k=0; k<len; k++) {
31             //res.append((cur.charAt(k)+j>'z')? ('a'+(int)(cur.charAt(k)+j-'z')-1) : (cur.charAt(k)+j));
32             char c = cur.charAt(k);
33             res.append((c-'a'-dist+26)%26+'a');
34         }
35         return res.toString();
36     }
37 }

 

posted @ 2015-12-22 02:04  neverlandly  阅读(443)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3