- 很典型的 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");