zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    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:

    1. S.length <= 10000
    2. S[i] is "(" or ")"
    3. S is a valid parentheses string

    Analyse

    给定一个由()构成的字符串,删去合法括号字符子串的最外面的括号

    合法括号字符串的定义:(AB都是合法字符串)

    • ("")
    • "(" + A + ")"
    • A + B

    思路就是删除掉遇到的第一对括号

    (()())(())

    读到第一个(时删掉,并删掉与之对应的)

    Code

    使用left来记录读到的(的个数,left为0说明这个(是第一次读到,应该和对应的)一起删去

    读到)时和(匹配,将left -1

    string removeOuterParentheses(string S)
    {
        string result;
        int left = 0;
        for (int i = 0; i < S.size(); i++)
        {
            if (S[i] == '(')
            {
                if (left++ != 0)
                {
                    result += '(';
                }
            }
            else if (S[i] == ')')
            {
                if (--left != 0)
                {
                    result += ')';
                }
            }
        }
    
        return result;
    }
    

    Result

    就LeetCode来看,这已经是最优解了,算法复杂度(O(N))

    Runtime: 4 ms, faster than 100.00% of C++ online submissions for Remove Outermost Parentheses.
    Memory Usage: 8.9 MB, less than 100.00% of C++ online submissions for Remove Outermost Parentheses.

  • 相关阅读:
    解方程
    十进制快速幂
    comb
    题单解题记录-POJ题目分类推荐 (很好很有层次感)
    算法题离谱错误合集
    VMware-Ubuntu16.04踩坑解决记录
    2020牛客多校赛第三场
    需学习的博客地址
    错误记录
    可持久化线段树 区间第k大/小
  • 原文地址:https://www.cnblogs.com/arcsinw/p/10738595.html
Copyright © 2011-2022 走看看