Remove Outermost Parentheses

Remove Outermost Parentheses

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<sub>1</sub> + P<sub>2</sub> + ... + P<sub>k</sub>, where P<sub>i</sub> are primitive valid parentheses strings.

Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.

LeetCode Problem - 1021

import java.util.Stack;

class Solution {
    // Method to remove outermost parentheses from a given string
    public String removeOuterParentheses(String s) {
        // StringBuilder to store the result
        StringBuilder ans = new StringBuilder();

        // Stack to keep track of parentheses
        Stack<Character> stack = new Stack<>();

        // Iterate through the characters of the string
        for (int i = 0; i < s.length(); i++) {
            char currentChar = s.charAt(i);

            // If current character is '(', check if it's not the outermost '('
            if (currentChar == '(') {
                if (!stack.isEmpty()) {
                    ans.append(currentChar);
                }
                stack.push(currentChar);
            } 
            // If current character is ')', check if it's not the outermost ')'
            else {
                stack.pop();
                if (!stack.isEmpty()) {
                    ans.append(currentChar);
                }
            }
        }

        // Return the result as a string
        return ans.toString();
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!