• [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.

  • 相关阅读:
    JavaScript 简介
    HTML 标签列表
    HTML5 是什么
    初识HTML5
    Conda 环境增删改查导出导入
    Windows 下安装 CGAL 并验证安装
    3D 点云数据集整理分析
    内网穿透
    SSH 免密登录
    串口、COM口、TTL、RS-232、RS-485区别详解
  • 原文地址:https://www.cnblogs.com/arcsinw/p/10738595.html
Copyright © 2020-2023  润新知