|
| 1 | +/********** ********** |
| 2 | +1021. Remove Outermost Parentheses |
| 3 | +A valid parentheses string is either empty (""), "(" + A + ")", or A + B, |
| 4 | +where A and B are valid parentheses strings, and + represents string concatenation. |
| 5 | +For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. |
| 6 | +A valid parentheses string S is primitive if it is nonempty, |
| 7 | +and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings. |
| 8 | +Given a valid parentheses string S, |
| 9 | +consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings. |
| 10 | +Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S. |
| 11 | + |
| 12 | +Example 1: |
| 13 | +Input: "(()())(())" |
| 14 | +Output: "()()()" |
| 15 | +Explanation: |
| 16 | +The input string is "(()())(())", with primitive decomposition "(()())" + "(())". |
| 17 | +After removing outer parentheses of each part, this is "()()" + "()" = "()()()". |
| 18 | + |
| 19 | +Example 2: |
| 20 | +Input: "(()())(())(()(()))" |
| 21 | +Output: "()()()()(())" |
| 22 | +Explanation: |
| 23 | +The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". |
| 24 | +After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". |
| 25 | + |
| 26 | +Example 3: |
| 27 | +Input: "()()" |
| 28 | +Output: "" |
| 29 | +Explanation: |
| 30 | +The input string is "()()", with primitive decomposition "()" + "()". |
| 31 | +After removing outer parentheses of each part, this is "" + "" = "". |
| 32 | + |
| 33 | +Note: |
| 34 | +S.length <= 10000 |
| 35 | +S[i] is "(" or ")" |
| 36 | +S is a valid parentheses string |
| 37 | +********** **********/ |
| 38 | + |
| 39 | + |
| 40 | +class Solution { |
| 41 | + public String removeOuterParentheses(String S) { |
| 42 | + int len = S.length(); |
| 43 | + int count = 0; |
| 44 | + int begin = 0; |
| 45 | + int end = 0; |
| 46 | + StringBuilder s = new StringBuilder(); |
| 47 | + |
| 48 | + for (int i = 0; i < len; i ++) { |
| 49 | + char c = S.charAt(i); |
| 50 | + if (c == '(') { |
| 51 | + count ++; |
| 52 | + } |
| 53 | + else { |
| 54 | + count --; |
| 55 | + } |
| 56 | + if (count == 0) { |
| 57 | + end = i; |
| 58 | + s.append(S.substring(begin + 1, end)); |
| 59 | + begin = end + 1; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return s.toString(); |
| 64 | + } |
| 65 | +} |
0 commit comments