LeetCode1021.Remove Outermost Parentheses(删除最外层的括号)
1021.Remove Outermost Parentheses(删除最外层的括号)
Description
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
.
有效括号字符串为空 ("")
、"(" + A + ")"
或 A + B
,其中 A
和 B
都是有效的括号字符串,+ 代表字符串的连接。例如,""
,"()"
,"(())()"
和 "(()(()))"
都是有效的括号字符串。
如果有效字符串 S
非空,且不存在将其拆分为 S = A+B
的方法,我们称其为原语(primitive),其中 A
和 B
都是非空有效括号字符串。
给出一个非空有效字符串 S
,考虑将其进行原语化分解,使得:S = P_1 + P_2 + ... + P_k
,其中 P_i
是有效括号字符串原语。
对 S
进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S
。
题目链接:https://leetcode.com/problems/remove-outermost-parentheses/
个人主页:http://redtongue.cn or https://redtongue.github.io/
Difficulty: easy
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:
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
分析
- 用index记录匹配的左右括号的数目,负数代表左括号“(”比右括号“)”多,绝对值代表多的数目;
- 遍历S,res存储删除最外层括号的结果,若index=0且当前字符为“(”,index-=1,继续;
- 若index=-1,且当前字符为“)”,index+=1,继续,(这是匹配到最外层括号的情况);
- 反之当前字符加到res中,若当前字符为“(”,index-=1,反之,index+=1;
- 返回res。
参考代码
class Solution(object):
def removeOuterParentheses(self, S):
res=''
index=0
for s in S:
if(index==0 and s=='('):
index-=1
continue
elif(index==-1 and s==')'):
index+=1
continue
else:
res+=s
if(s=='('):
index-=1
else:
index+=1
return res
上一篇: 二分算法总结