[LeetCode] 249. Group Shifted Strings

本文介绍了一种用于将字符串根据其移位序列进行分组的算法。该算法通过计算字符串中各字符间的相对位置,将其转换为一组统一的特征,从而能够有效地将属于同一移位序列的字符串归类到一起。示例代码展示了如何使用哈希映射来实现这一过程。

Problem

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.

Example:

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

Solution

class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str: strings) {
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i < str.length(); i++) {
                int diff = str.charAt(i)-str.charAt(i-1);
                if (diff < 0) diff += 26;
                sb.append('a'+diff); //***** 'a' *****
            }
            String key = sb.toString();
            map.putIfAbsent(key, new ArrayList<>());
            map.get(key).add(str);
        }
        return new ArrayList<>(map.values());
    }
}

//["an","bcf"]
//keys: 110, 98100
//result: [["an"],["bcf"]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值