leetcode 1021. Remove Outermost Parentheses (python)

357 阅读2分钟

leetcode 1021. Remove Outermost Parentheses (python)

描述

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:

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

解析

根据题意,合法的括号子字符串就是左右括号数相等即可,然后去掉最外层的左右括号,将剩下的合法的括号子字符串都拼接起来返回即可,具体看例子一就可清楚。其实和以前的括号题一样,只需要通过对左括号计数加一,对右括号计数减一,当计数器变为零的时候,表示找到一组合法的括号子字符串,然后只截取除最外层括号外的字符串追加到 res 中即可,继续遍历后面的字符串执行如上相同的操作,遍历结束得到的 res 即为结果。

解答

class Solution(object):
    def removeOuterParentheses(self, S):
        """
        :type S: str
        :rtype: str
        """
        count = 0
        res = ''
        idx = 0
        for i, c in enumerate(S):
            if c == '(':
                count += 1
            elif c == ')':
                count -= 1
            if count == 0:
                res += S[idx + 1: i]
                idx = i + 1
        return res
        	      
		

运行结果

Runtime: 24 ms, faster than 91.36% of Python online submissions for Remove Outermost Parentheses.
Memory Usage: 13.8 MB, less than 66.24% of Python online submissions for Remove Outermost Parentheses.

原题链接:leetcode.com/problems/re…

您的支持是我最大的动力