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"]
A solution is:

[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]

 


题目标签:Hash Table

  题目给了我们一个 strings array,让我们把不同移位距离的string 分开归类。

  首先来看一下相同移位距离string 的特性:

    相同的移位string,拥有相同的移位距离,比如abc, bcd, xyz 都是移位了1个距离。根据这个特性,我们可以把bcd 和 xyz 恢复到 abc。

  利用HashMap,把最原始的 归位string 当作key,把可以恢复到 原始的 归位string 的 所有strings(List)当作value 存入map。

  

 

 

Java Solution:

Runtime beats 44.74% 

完成日期:11/04/2017

关键词:HashMap

关键点:利用 char - 'a' 把所有相同移位距离的strings 转换成 同一个原始string 存入map

 1 class Solution 
 2 {
 3     public List<List<String>> groupStrings(String[] strings) 
 4     {
 5         List<List<String>> res = new ArrayList<>();
 6         
 7         HashMap<String, List<String>> map = new HashMap<>();
 8         
 9         // store original string as key; (List) strings come from same original one as value
10         for(String str: strings)
11         {
12             int offset = str.charAt(0) - 'a';
13             String key = "";
14             
15             for(int i=0; i<str.length(); i++)
16             {
17                 char c = (char) (str.charAt(i) - offset);
18                 if(c < 'a')
19                     c += 26;
20                 
21                 key += c;
22             }
23              
24             if(!map.containsKey(key))
25                 map.put(key, new ArrayList<String>());
26              
27             map.get(key).add(str);
28             
29         }
30         
31         // add each key's value into res
32         for(String key: map.keySet())
33         {
34             res.add(map.get(key));
35         }
36         
37         return res;
38     }
39 }

参考资料:

https://discuss.leetcode.com/topic/20722/my-concise-java-solution

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2017-11-05 06:26  Jimmy_Cheng  阅读(416)  评论(0编辑  收藏  举报