Skip to content

Latest commit

 

History

History
47 lines (42 loc) · 1.29 KB

1190.反转每对括号间的子串.md

File metadata and controls

47 lines (42 loc) · 1.29 KB

解题关键点

  • 很典型的 stack 问题,遇到 "(" 就压栈,遇到 ")" 就出栈并反转

代码

impl Solution {
    pub fn reverse_parentheses(s: String) -> String {
        // 使用向量模拟 stack
        let mut stack: Vec<String> = Vec::new();
        let mut top = String::new();
        for i in s.chars() {
            // match 对应 js 中的 switch
            match i {
                '(' => {
                    // 压栈
                    stack.push(top);
                    top = String::new();
                }
                ')' => {
                    // rust 反转字符串可太简单了
                    let end: String = top.chars().rev().collect();
                    // 出栈
                    top = stack.pop().unwrap();
                    // 拼接
                    top.push_str(&end);
                }
                // _ 对应 switch 中的 default
                _ => {
                    top.push(i);
                }
            }
        }
        top
    }
}

测试用例

assert_eq!(reverse_parentheses("abc".to_string()), "abc");
assert_eq!(reverse_parentheses("(abc)".to_string()), "cba");
assert_eq!(reverse_parentheses("((abc))".to_string()), "abc");
assert_eq!(reverse_parentheses("((ab)c)".to_string()), "cab");