Leetcode 0249: 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 non-empty strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.

Example 1:

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

Time complexity: O()
对于每个不同长度的string 以最第一个字母为‘a’的字符串作为key。例,长度唯一的字符串,以“a“ 作为key,长度为2的字符串 “az”, “ba” 以 “az” 作为key,长度为3的字符串 “abc”, “bcd”, “xyz” 以 “abc” 作为key,观察每个长度的字符串和 key 之间的关系:key字符串和其相同组的字符串的每个字母的差值都是一样的。例如:长度为3的字符"abc", “bcd”, “xyz” 以 “abc” 作为key。 比较 “bcd” 和 key “abc” 则: ‘b’ - ‘a’ = ‘c’ - 'b’ = ‘d’ - ‘c’ = offset = 1.

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

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113916936