LeetCode每日一题(1190. Reverse Substrings Between Each Pair of Parentheses)

本文介绍了一种算法,该算法能将字符串中每一对匹配的括号内的内容进行逆序排列,从最内层括号开始逆序,直至整个字符串。通过递归方式实现,确保最终结果不含括号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given a string s that consists of lower case English letters and brackets.

Reverse the strings in each pair of matching parentheses, starting from the innermost one.

Your result should not contain any brackets.

Example 1:

Input: s = “(abcd)”
Output: “dcba”

Example 2:

Input: s = “(u(love)i)”
Output: “iloveu”

Explanation: The substring “love” is reversed first, then the whole string is reversed.

Example 3:

Input: s = “(ed(et(oc))el)”
Output: “leetcode”

Explanation: First, we reverse the substring “oc”, then “etco”, and finally, the whole string.

Constraints:

  • 1 <= s.length <= 2000
  • s only contains lower case English characters and parentheses.
  • It is guaranteed that all parentheses are balanced.

没有太多可说的, 整体思路是,如果我们把一个字符串外层包裹的括号数量作为层级, 那具有有数层括号的字符串是不用翻转的, 因为翻转再翻转等于原字符串


impl Solution {
    fn rc(chars: &Vec<char>, i: &mut usize, reverse: bool) -> String {
        let mut buffer = String::new();
        while *i < chars.len() {
            match chars[*i] {
                '(' => {
                    *i += 1;
                    if reverse {
                        buffer.insert_str(0, &Solution::rc(chars, i, !reverse));
                        continue;
                    }
                    buffer.push_str(&Solution::rc(chars, i, !reverse));
                }
                ')' => {
                    *i += 1;
                    return buffer;
                }
                _ => {
                    if reverse {
                        buffer.insert(0, chars[*i]);
                        *i += 1;
                        continue;
                    }
                    buffer.push(chars[*i]);
                    *i += 1;
                }
            }
        }
        buffer
    }
    pub fn reverse_parentheses(s: String) -> String {
        Solution::rc(&s.chars().collect(), &mut 0, false)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值