← 返回 google 的题目列表Group Strings with Same Shift-Distance (Group Shifted Strings)
类型:online_judge
Problem (Coding)
Given a list of strings strings (lowercase letters a-z only), group together strings that share the same distance / shift pattern, and return all groups.
Two strings belong to the same group iff:
They have the same length, and
Their adjacent-character difference sequence is identical.
Formally, for a string s, define its distance pattern as:
For each i (0 <= i < len(s)-1), compute
d[i] = (ord(s[i+1]) - ord(s[i]) + 26) % 26
If two strings have the exact same difference sequence, they have the same distance pattern.
Examples:
"aaa" and "zzz" are in the same group (pattern [0, 0]).
"abc" and "bcd" are in the same group (pattern [1, 1]).
"az" and "ba" are in the same group (pattern [25], using wrap-around).
Output
Return a list of groups (2D list).
The order of groups and the order within each group do not matter unless specified otherwise.
Constraints (for discussion)
1 <= len(strings) <= 1e4
1 <= len(strings[i]) <= 1e2
Example
Input:
["aaa", "zzz", "abc", "bcd", "acef", "az", "ba", "a", "z"]
One valid output (order may vary):
["aaa", "zzz"]
["abc", "bcd"]
["az", "ba"]
["acef"]
["a", "z"]
Example
Input
aaa zzz abc bcd acef az ba a z
Output
[["aaa","zzz"],["abc","bcd"],["acef"],["az","ba"],["a","z"]]