|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/**1021. Remove Outermost Parentheses |
| 7 | + * |
| 8 | + * 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. |
| 9 | + * |
| 10 | + * 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. |
| 11 | + * |
| 12 | + * 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. |
| 13 | + * |
| 14 | + * Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S. |
| 15 | + * |
| 16 | + * |
| 17 | + * Example 1: |
| 18 | + * Input: "(()())(())" |
| 19 | + * Output: "()()()" |
| 20 | + * Explanation: |
| 21 | + * The input string is "(()())(())", with primitive decomposition "(()())" + "(())". |
| 22 | + * After removing outer parentheses of each part, this is "()()" + "()" = "()()()". |
| 23 | + * |
| 24 | + * Example 2: |
| 25 | + * Input: "(()())(())(()(()))" |
| 26 | + * Output: "()()()()(())" |
| 27 | + * Explanation: |
| 28 | + * The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". |
| 29 | + * After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". |
| 30 | + * |
| 31 | + * Example 3: |
| 32 | + * Input: "()()" |
| 33 | + * Output: "" |
| 34 | + * Explanation: |
| 35 | + * The input string is "()()", with primitive decomposition "()" + "()". |
| 36 | + * After removing outer parentheses of each part, this is "" + "" = "". |
| 37 | + * |
| 38 | + * Note: |
| 39 | + * |
| 40 | + * S.length <= 10000 |
| 41 | + * S[i] is "(" or ")" |
| 42 | + * S is a valid parentheses string |
| 43 | + * */ |
| 44 | +public class _1021 { |
| 45 | + public static class Solution1 { |
| 46 | + public String removeOuterParentheses(String S) { |
| 47 | + List<String> primitives = new ArrayList<>(); |
| 48 | + for (int i = 1; i < S.length(); i++) { |
| 49 | + int initialI = i - 1; |
| 50 | + int left = 1; |
| 51 | + while (i < S.length() && left > 0) { |
| 52 | + if (S.charAt(i) == '(') { |
| 53 | + left++; |
| 54 | + } else { |
| 55 | + left--; |
| 56 | + } |
| 57 | + i++; |
| 58 | + } |
| 59 | + primitives.add(S.substring(initialI, i)); |
| 60 | + } |
| 61 | + StringBuilder sb = new StringBuilder(); |
| 62 | + for (String primitive : primitives) { |
| 63 | + sb.append(primitive.substring(1, primitive.length() - 1)); |
| 64 | + } |
| 65 | + return sb.toString(); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments