Member-only story
Solution to Leetcode 1021 Remove Outermost Parentheses
In this problem, we are asked to remove the top level parentheses from a string of parentheses, such that (A)(B)(C)(D)
becomes ABCD
.
The approach I took, was to have a counter
, and to add 1
when the character encountered was (
and remove one otherwise (character )
).
That way, when the counter is 0
, we must encounter (
and remove it from the string. The same happens when the counter is 1
and we encounter )
.
For instance the string “(()())(())”
, will have the following sequence of counters:
0 (before starting) -> remove the first character, 1, 2, 1, 2, 1 -> and encounter ')', remove character, 0 -> remove character, 1, 2, 1 -> and encountering ')', remove the last character, 0 (after scanning the last character)
The code in Go is the following:
func removeOuterParentheses(S string) string {
var res bytes.Buffer
counter := 0
for _,c := range S {
if counter != 0 && !(counter == 1 && c == ')') {
res.WriteRune(c)
}
if c == '(' {
counter++
} else {
counter--
}
}
return res.String()
}