Easy Solution 🧩 A Step-by-Step Guide in Java, Python, and C++ 📚
Intuition\nTo solve the problem of removing outermost parentheses, the main idea is to track the balance of parentheses using a counter. When traversing the str
# Intuition\nTo solve the problem of removing outermost parentheses, the main idea is to track the balance of parentheses using a counter. When traversing the string, we use the counter to determine if the current parenthesis is part of the outermost pair. If it is not, we add it to the result string.\n\n# Approach\n1. Initialize:\n\n- Use a StringBuilder (or equivalent) to build the result string efficiently.\n- Use a counter to track the depth of parentheses.\n2. Loop Through the String:\n\n- For each character in the input string:\n- If it\'s a closing parenthesis ), decrease the counter first.\n- If the counter is not zero, append the character to the result.\n- If it\'s an opening parenthesis (, increase the counter after the check.\n3. Return the Result:\n\n- Convert the StringBuilder to a string and return it.\n\n# Complexity\n- Time complexity: The time complexity is O(n), where \uD835\uDC5B is the length of the input string s, since we process each character exactly once.\n\n- Space complexity:\nThe space complexity is O(n) due to the space used by the StringBuilder to store the result.\n\n# Code\n\n```java []\nclass Solution {\n    public String removeOuterParentheses(String s) {\n        StringBuilder ans = new StringBuilder();\n        int count = 0;\n\n        for(int i=0; i<s.length(); i++) {\n            char c = s.charAt(i);\n            if(c == \')\') count--;\n            if(count !=0) ans.append(c);\n            if(c == \'(\') count++;\n        }\n    return ans.toString();\n    }\n}\n```\n```python []\nclass Solution:\n    def removeOuterParentheses(self, s: str) -> str:\n        ans = []\n        count = 0\n\n        for char in s:\n            if char == \')\':\n                count -= 1\n            if count != 0:\n                ans.append(char)\n            if char == \'(\':\n                count += 1\n\n        return \'\'.join(ans)\n```\n```C++ []\nclass Solution {\npublic:\n    std::string removeOuterParentheses(std::string s) {\n        std::string ans;\n        int count = 0;\n\n        for(char c : s) {\n            if(c == \')\') count--;\n            if(count != 0) ans += c;\n            if(c == \'(\') count++;\n        }\n        return ans;\n    }\n};\n```\n```
['String', 'C++', 'Java', 'Python3']