mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
go: add «1190. Reverse Substrings Between Each Pair of Parentheses»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
5f3765f37a
commit
f6b4c01bbd
1 changed files with 36 additions and 0 deletions
36
go/reverse-substrings-between-each-pair-of-parentheses.go
Normal file
36
go/reverse-substrings-between-each-pair-of-parentheses.go
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
func reverseParentheses(s string) string {
|
||||||
|
getParentheses := func() []int {
|
||||||
|
pairing := make([]int, len(s))
|
||||||
|
|
||||||
|
opened := make([]int, 0, len(s)/2)
|
||||||
|
for i, c := range s {
|
||||||
|
if c == '(' {
|
||||||
|
opened = append(opened, i)
|
||||||
|
} else if c == ')' {
|
||||||
|
var j int
|
||||||
|
j, opened = opened[len(opened)-1], opened[:len(opened)-1]
|
||||||
|
|
||||||
|
pairing[i] = j
|
||||||
|
pairing[j] = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return pairing
|
||||||
|
}
|
||||||
|
|
||||||
|
pairing := getParentheses()
|
||||||
|
|
||||||
|
result := make([]byte, 0, len(s))
|
||||||
|
for i, d := 0, 1; i < len(s); i += d {
|
||||||
|
if s[i] == '(' || s[i] == ')' {
|
||||||
|
i = pairing[i]
|
||||||
|
d *= -1
|
||||||
|
} else {
|
||||||
|
result = append(result, s[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(result)
|
||||||
|
}
|
Loading…
Reference in a new issue