LeetCode算法题1021解题思路

原题

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:

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

Example 2:

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

Example 3:

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

Note:

  • S.length <= 10000
  • S[i] is “(“ or “)”
  • S is a valid parentheses string

思路

看到这题,我就想起了用栈的方式来匹配括号。
一个slice A存左括号,然后遍历的过程中遇到一个左括号就添加到这个slice A里面,遇到右括号则删除尾部的一个左括号;
如果删除之后slice A为空,则说明匹配到了一组primitive decomposition.
而另一个slice B存遍历过程中每一组primitive decomposition, 就是遍历过程中不管是左括号还是右括号,都要存下来;并且,当上面所说的slice A为空之后,就把slice B的数据追加到一个字符串S中,不过需要去除最外层的括号,即B[1:len(B)-1]。然后再清空slice B,准备接收下一组括号。
这样,当循环结束后返回S即可。

代码实现

Golang实现

https://github.com/cook-coder/my-leetcode-solution/tree/master/easy/1021

成绩

总结

这道题的失误之处在于陷入了惯性思维,一开始就想到用栈的方式取解决问题。
实际上栈的话应该用在检验括号匹配是否合法,而仔细阅读本题,你会发现,题目已经保证了括号匹配的合法性。所以可以用更简单的方式去实现,我也在代码里把别人的实现写上了,真的是非常简练和高效。

加载评论框需要科学上网