From 09ff307ea01b35f81704c196b7f8567e544d2d57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Khoa=20Hu=E1=BB=B3nh=20=28Daniel=29?= Date: Sat, 6 Apr 2024 23:02:32 +0700 Subject: [PATCH] Update 1249 --- solution/1249/main.go | 45 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 solution/1249/main.go diff --git a/solution/1249/main.go b/solution/1249/main.go new file mode 100644 index 0000000..8331f02 --- /dev/null +++ b/solution/1249/main.go @@ -0,0 +1,45 @@ +package main + +type stack struct { + top int + v []byte + index []int +} + +func minRemoveToMakeValid(s string) string { + stc := stack{top: -1} + + // collect bad brackets + for i, v := range s { + if v == '(' { + stc.v = append(stc.v, '(') + stc.index = append(stc.index, i) + stc.top++ + } else if v == ')' { + if stc.top > -1 && stc.v[stc.top] == '(' { + stc.v = stc.v[:stc.top] + stc.index = stc.index[:stc.top] + stc.top-- + } else { + stc.v = append(stc.v, ')') + stc.index = append(stc.index, i) + stc.top++ + } + } + } + + // remove them + res := []byte{} + i := 0 + for _, v := range stc.index { + res = append(res, s[i:v]...) + i = v + 1 + } + + // checking of end + if len(res) + len(stc.index) < len(s) { + res = append(res, s[i:]...) + } + + return string(res) +}