【leetcode - 1021】删除最外层括号 -Easy
【original】
思路:
stack里面每次进入一个变量,等到栈内左括号和右括号数目相同的时候去掉标记的位置的左括号和最后一位的右括号,更新标记为当前位置,继续循环。合并剩余内容。
代码:
class Solution: def removeOuterParentheses(self, S: str) -> str: stack = [] res = "" left, right = 0, 0 mark = 0 for i in S: if i == "(": left +=1 stack.append("(") else: right +=1 stack.append(")") if left == right: res+="".join(stack[mark+1:-1]) mark = left+right return res
【other】
思路:
initial 变量和栈,如果是左括号,且为第一个,则stack中长度为1,不进入最终输出变量中。如果为右括号,去掉栈内的左括号,如果判断栈内长度为0,则为最后一个右括号,不进入最终变量中。
def removeOuterParentheses(self, S: str) -> str: res = '' stack = [] for i in S: if i == "(": stack.append("(") if len(stack)!=1: res+="(" else: stack.pop() if len(stack)!=0: res+=")" return res
浙公网安备 33010602011771号