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)
}
}