Group Shifted Strings

https://leetcode.com/problems/group-shifted-strings/description/

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

]

Thoughts

字符之间间隔存在规律, 统计出来作为key就好了. 由于是circular的, 当str[i] < str[i - 1]时直接加26.

Code

Analysis

时间复杂度O(MN). M为单词长度.

Last updated

Was this helpful?