249. 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"],
A solution is:

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

Solution:

思路: 将strs按照规律编码Map(code_str -> list(string)) 归到不同类,输出各list(string)。
区别他们不同的是str的length 和 他们在字符表中之间的相对位置,shift后也不变。
相对位置可以 以 第一个字符在字符表中的位置 做参照标准(encode1) 或以 前一个字符在字符表中的位置 为参照坐标(encode2)

Time Complexity: O(mn) Space Complexity: O(mn) 不算结果
m个str,长度为n

Solution Code:

class Solution {
    public List> groupStrings(String[] strings) {
        List> result = new ArrayList>();
        Map> map = new HashMap>();
        
        //encode
        for (String str : strings) {
            String key = encode1(str);
            if (!map.containsKey(key)) {
                List list = new ArrayList();
                map.put(key, list);
            }
            map.get(key).add(str);
        }
        
        // prepare the result
        for (String key : map.keySet()) {
            List list = map.get(key);
            // Collections.sort(list);
            result.add(list);
        }
        return result;
    }
    
    private String encode1(String str) {
        String key = "";
        for (int i = 0; i < str.length(); i++) {
            char c = (char) (str.charAt(i) - str.charAt(0) + 'a');
            if (c < 'a') c += 26;
            key += c;
        }
        return key;
    }
    private String encode2(String str) {
        String key = "";
        for (int i = 0; i < str.length(); i++) {
            char c = (char) (str.charAt(i) - str.charAt(0) + 'a');
            if (c < 'a') c += 26;
            key += c;
        }
        return key;
    }
}

你可能感兴趣的:(249. Group Shifted Strings)