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

posted @ 2019-04-19 20:27  arcsinW  阅读(394)  评论(0编辑  收藏  举报