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,那么我们需要有一个规则,把符合规则的放在一起。那么,规则是什么呢?

根据题目的意思,对于两串字符串,如果字符串的相邻字符的差值是一致的,那么我们就可以把它们放在一起。

但是对于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 }

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5717873.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值