Leetcode 1021. Remove Outermost Parentheses
Given a valid parentheses string, s
, you need to remove the outermost parentheses of every primitive string in the primitive decomposition of s
. A primitive string is a non-empty string that cannot be split into two non-empty valid parentheses strings.
s = "(()())(())"
"()()()"
s
?
s
will be between 1 and 10,000.The goal is to iterate through the string while maintaining a counter to track the nesting level of the parentheses to identify the outermost ones. Here’s the approach step-by-step:
count
to keep track of the balance between (
and )
.result
to store the modified string without the outermost parentheses.s
.(
:
count
is greater than 0, append (
to the result (indicating it’s not the outermost (
).count
.)
:
count
.count
is greater than 0, append )
to the result (indicating it’s not the outermost )
).count
variable ensures that we correctly identify the outermost parentheses in each primitive segment.#include <string>
using namespace std;
class Solution {
public:
string removeOuterParentheses(string s) {
string result = "";
int count = 0;
for (char c : s) {
if (c == '(') {
if (count > 0) {
result += c;
}
count++;
} else {
count--;
if (count > 0) {
result += c;
}
}
}
return result;
}
};
The time complexity of the provided solution is O(n), where n
is the length of the string s
. This is because we only iterate over the string once.
The space complexity is O(n) as well due to storing the resultant string without the outermost parentheses.
If there are any further questions or unclear points, feel free to ask!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?