原題連接在這裏:https://leetcode.com/problems/group-shifted-strings/html
題目:app
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:post
"abc" -> "bcd" -> ... -> "xyz"
Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.ui
For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]
,
A solution is:spa
[ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ]
題解:code
與Group Anagrams相似. 維護一個HashMap, key是每一個string 的 base型.orm
Time Complexity: O(n * strings.length), n 是每一個string的平均長度.htm
Space: O(hm.size()), HashMap size.blog
AC Java:leetcode
1 public class Solution { 2 public List<List<String>> groupStrings(String[] strings) { 3 if(strings == null || strings.length == 0){ 4 return new ArrayList<List<String>>(); 5 } 6 7 HashMap<String, List<String>> hm = new HashMap<String, List<String>>(); 8 for(String str : strings){ 9 String base = getBase(str); 10 if(!hm.containsKey(base)){ 11 List<String> ls = new ArrayList<String>(); 12 hm.put(base, ls); 13 } 14 hm.get(base).add(str); 15 } 16 17 return new ArrayList<List<String>>(hm.values()); 18 } 19 20 private String getBase(String s){ 21 if(s == null || s.length() == 0){ 22 return s; 23 } 24 25 StringBuilder sb = new StringBuilder(); 26 int offset = s.charAt(0) - 'a'; 27 for(int i = 0; i<s.length(); i++){ 28 char c = (char)(s.charAt(i) - offset); 29 if(c < 'a'){ 30 c += 26; 31 } 32 sb.append(c); 33 } 34 return sb.toString(); 35 } 36 }