249. Group Shifted Strings

51 篇文章 0 订阅
36 篇文章 0 订阅

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"]
]
这道题让把所有可以shift的字符串分组。首先想到得给某一类字符串找一个标准字符串,可以都把首字母shift 到‘a’ 上,后面的字母依次shift,然后用hashmap判断有没有这个字符串生成的标准字符串,有的话在list后面加上这个字符串,没有的话,创建一个新key和对应的新list,最后返回结果。代码如下:
public class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
        //List<List<String>> rlist = new ArrayList<List<String>>();
        for(String str:strings) {
            int offset = str.charAt(0) - 'a';
            String temp = "";
            for (char ch:str.toCharArray()) {
                if (ch - offset < 'a') {
                    temp += (ch - offset + 26);
                } else {
                    temp += (ch - offset);
                }
            }
            if (!hm.containsKey(temp)) {
                hm.put(temp, new ArrayList<String>());
            }
            hm.get(temp).add(str);
        }
        /*for (String key:hm.keySet()) {
            List<String> templist = hm.get(key);
            Collections.sort(templist);
            rlist.add(templist);
        }*/
        //上面一大段可以用下面这一句代替
        return new ArrayList<List<String>>(hm.values());
    }
}
标准字符串的生成方法也可以采用后一个字母和前一个字母的差,代码如下:

public List<List<String>> groupStrings(String[] strs) {
	HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
    Arrays.sort(strs);    	
	for (String s : strs) {
		String key = "";
		for (int i = 1; i < s.length(); i++) 
			key += String.format("%2d", (s.charAt(i) - s.charAt(i-1) + 26) % 26);//Difference from the previous char.
		if (!map.containsKey(key)) map.put(key, new ArrayList<String>());
		map.get(key).add(s);    		
	} 
	return new ArrayList<List<String>>(map.values());
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值