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,那么我们需要有一个规则,把符合规则的放在一起。那么,规则是什么呢?
根据题目的意思,对于两串字符串,如果字符串的相邻字符的差值是一致的,那么我们就可以把它们放在一起。
但是对于az, ba这样的,字符之间的差值不一样啊。但是为何它们是一组的呢?
az字符之间的差值是25,ba之间字符的差值是-1,但是字符是每隔26就一循环,所以,对于-1,你一旦加上26就是25.
1 public class Solution { 2 public List<List<String>> groupStrings(String[] strings) { 3 List<List<String>> result = new ArrayList<List<String>>(); 4 HashMap<String, List<String>> map = new HashMap<String, List<String>>(); 5 for (int i = 0; i < strings.length; i++) { 6 StringBuffer sb = new StringBuffer(); 7 for (int j = 0; j < strings[i].length(); j++) { 8 sb.append(Integer.toString(((strings[i].charAt(j) - strings[i].charAt(0)) + 26) % 26)); 9 sb.append(" "); 10 } 11 String shift = sb.toString(); 12 13 if (map.containsKey(shift)) { 14 map.get(shift).add(strings[i]); 15 } else { 16 List<String> list = new ArrayList<String>(); 17 list.add(strings[i]); 18 map.put(shift, list); 19 } 20 } 21 22 for (String s : map.keySet()) { 23 Collections.sort(map.get(s)); 24 result.add(map.get(s)); 25 } 26 return result; 27 } 28 }