Amazon VO 面试真题解析:括号内字符串逐层反转(Reverse Substrings Between Each Pair of Parentheses)

31次阅读
没有评论

Given a string s containing only lowercase English letters and parentheses, reverse the strings in each pair of matching parentheses from the innermost to the outermost, and return the final result.

Note that your result should not contain any parentheses.

Example 1:

Input: s = "(abcd)"
Output: "dcba"

Example 2:

Input: s = "(u(love)i)"
Output: "iloveu"

Explanation: First, reverse the substring “love”, then reverse the entire string.

这道题的核心是按括号层级从内到外处理字符串:遇到一对匹配括号,就把其中的子串反转,再继续向外合并。常见做法是用栈或递归先找到每一层括号的对应关系,再遍历字符串构造结果;也可以用“括号配对 + 方向切换”的思路在线性时间内完成。题目强调最终结果不能保留任何括号,因此在拼接时需要跳过括号字符,只输出反转后的字母序列。

正文完
 0