|
| 1 | +/* |
| 2 | +1021. Remove Outermost Parentheses |
| 3 | +
|
| 4 | +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. |
| 5 | +
|
| 6 | +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. |
| 7 | +
|
| 8 | +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. |
| 9 | +
|
| 10 | +Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S. |
| 11 | +
|
| 12 | +
|
| 13 | +
|
| 14 | +Example 1: |
| 15 | +
|
| 16 | +Input: "(()())(())" |
| 17 | +Output: "()()()" |
| 18 | +Explanation: |
| 19 | +The input string is "(()())(())", with primitive decomposition "(()())" + "(())". |
| 20 | +After removing outer parentheses of each part, this is "()()" + "()" = "()()()". |
| 21 | +Example 2: |
| 22 | +
|
| 23 | +Input: "(()())(())(()(()))" |
| 24 | +Output: "()()()()(())" |
| 25 | +Explanation: |
| 26 | +The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". |
| 27 | +After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". |
| 28 | +Example 3: |
| 29 | +
|
| 30 | +Input: "()()" |
| 31 | +Output: "" |
| 32 | +Explanation: |
| 33 | +The input string is "()()", with primitive decomposition "()" + "()". |
| 34 | +After removing outer parentheses of each part, this is "" + "" = "". |
| 35 | +
|
| 36 | +
|
| 37 | +Note: |
| 38 | +
|
| 39 | +S.length <= 10000 |
| 40 | +S[i] is "(" or ")" |
| 41 | +S is a valid parentheses string |
| 42 | +
|
| 43 | +
|
| 44 | +
|
| 45 | +*/ |
| 46 | + |
| 47 | +// time: 2020-05-04 |
| 48 | + |
| 49 | +package removeoutmostparentheses |
| 50 | + |
| 51 | +// time complexity: O(n), where n is length of S. |
| 52 | +// space complexity: O(1) |
| 53 | +func removeOuterParentheses(S string) string { |
| 54 | + // S is valid parentheses string, so, s is empty "" or starts with "(" |
| 55 | + if len(S) == 0 { |
| 56 | + return S |
| 57 | + } |
| 58 | + |
| 59 | + var stackLength, left int |
| 60 | + |
| 61 | + var ret string |
| 62 | + |
| 63 | + for i := 0; i < len(S); i++ { |
| 64 | + if stackLength == 0 { |
| 65 | + left = i |
| 66 | + } |
| 67 | + if S[i] == '(' { |
| 68 | + stackLength++ |
| 69 | + } else { |
| 70 | + stackLength-- |
| 71 | + } |
| 72 | + if stackLength == 0 { |
| 73 | + ret += S[left+1 : i] |
| 74 | + } |
| 75 | + } |
| 76 | + return ret |
| 77 | +} |
0 commit comments