Meta VO 面试真题解析:Group Shifted Strings 字符串分组与位移模式

21次阅读
没有评论

Given a list of strings, find the groups of strings that can be rotated to each other (so each character is changed by the same distance).

Input: ['abc', 'bcd', 'bde', 'cef', 'efg', 'zab']

Output: [['abc', 'bcd', 'efg', 'zab'], ['bde', 'cef']]

Two strings are in the same group if every character in one string can be shifted by the same amount to obtain the other string, with wraparound from 'z' to 'a'.

这道题的核心是把每个字符串归一化成“相对位移模式”:例如 <code>abc</code>、<code>bcd</code>、<code>zab</code> 的字符差值模式都相同,因此属于同一组。实现时通常先把字符串转换成一个稳定的键,例如记录相邻字符之间的差值(按 26 取模),再用哈希表按键分组。这样可以在线性遍历所有字符串的同时完成分类,时间复杂度主要取决于字符串总长度。

正文完
 0