[LeetCode] 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"]
]

Thought process:
Hash table.
If two strings belong to the same shifting sequence, the differences between any consecutive pair of their characters are the same. We can use those differences as encoding for the strings.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        List<List<String>> groups = new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>();
        
        for (String s : strings) {
            String encoded = encode(s);
            if (!map.containsKey(encoded)) {
                map.put(encoded, new ArrayList<>());
            }
            map.get(encoded).add(s);
        }
        
        for (String key : map.keySet()) {
            groups.add(map.get(key));
        }
        return groups;
    }
    
    private String encode(String s) {
        if (s.length() == 1) {
            return "-1";
        }
        
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < s.length(); i++) {
            sb.append((s.charAt(i) + 26 - s.charAt(i - 1)) % 26);
        }
        return sb.toString();
    }
}

Time complexity:
Say the strings have an average length of l. The overall time complexity is O(ln).

Comments

  1. I have a bit doubt about the encoding method. Since (s.charAt(i) + 26 - s.charAt(i - 1)) % 26 could be either 1-digit or 2-digits, For example, the encoding for 'az' is '25', and the encoding for 'acg' is also '25', but obviously they should not belong to the same group.

    ReplyDelete
  2. To avoid duplicate I think we can add "." after each appended value in sb

    ReplyDelete
  3. 0cillumAco_na Travis Booth Download
    sighsotofor

    ReplyDelete

Post a Comment

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula