1021. Remove Outermost Parentheses

A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.

A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.

Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.

Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.

Example 1:

Input: "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".

Example 2:

Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".

Example 3:

Note:

解法

使用一个栈记录最外层括号的状态

保证栈中只有最外层的左括号,然后把内部的括号依次存入一个列表里,使用 count 记录内部左括号的数目,每遇到一个左括号 count 的值就加一,遇到一个右括号 count 的值减一。当遇到一个右括号并且 count 为0时到达最外层的右括号,此时将栈中的左括号 pop 出去即可。

()((()))

stack

final

count

(

(

0

)

0

(

(

0

(

(

(

1

(

(

((

2

)

(

(()

1

)

(

(())

0

)

(())

0

一个更简洁的解法

这个真的写的很棒了。

两种方法的时间复杂度和空间复杂度都是 O(n)O(n)

Last updated

Was this helpful?