249 Group Shifted Strings
1. Question
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"]
]2. Implementation
(1) HashMap
思路: 这里比较巧妙的做法是根据每个词的character和它之前的character的偏移量作为key. 注意由于a - z = -25, 为了让计算的结果统一为正数,我们需要对结果 + 26 再 模26
3. Time & Space Complexity
HashMap: 时间复杂度O(nL), 空间复杂度O(n)
Last updated
Was this helpful?