From f6b4c01bbd11696f68d2af1aaf900ad5f304b8ad Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 11 Jul 2024 15:29:12 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB1190.=20Reverse=20Substrings?= =?UTF-8?q?=20Between=20Each=20Pair=20of=20Parentheses=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...trings-between-each-pair-of-parentheses.go | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 go/reverse-substrings-between-each-pair-of-parentheses.go diff --git a/go/reverse-substrings-between-each-pair-of-parentheses.go b/go/reverse-substrings-between-each-pair-of-parentheses.go new file mode 100644 index 0000000..4104d5b --- /dev/null +++ b/go/reverse-substrings-between-each-pair-of-parentheses.go @@ -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) +}