The problem
On this problem, you may be given a string with brackets and an index of a gap bracket and your activity shall be to return the index of the matching closing bracket. Each the enter and returned index are 0-based. A gap brace will at all times have a closing brace. Return an error if there isn’t any reply.
Examples:
clear up("((1)23(45))(aB)", 0) = 10 // the opening brace at index 0 matches the closing brace at index 10
clear up("((1)23(45))(aB)", 1) = 3
clear up("((1)23(45))(aB)", 2) = -1 // there isn't any opening bracket at index 2, so return -1
clear up("((1)23(45))(aB)", 6) = 9
clear up("((1)23(45))(aB)", 11) = 14
clear up("((>)|?(*'))(yZ)", 11) = 14
Enter will encompass letters, numbers, and particular characters, however no areas. The one brackets shall be (
 and )
.
The answer in Golang
Possibility 1:
package deal answer;
import ("errors")
func Answer(s string, i uint) (uint, error) {
if s[i] == '(' {
d := 0;
for j := i+1; j < uint(len(s)); j++ {
c := s[j];
change {
case d==0 && c==')': return j, nil;
case c=='(': d++;
case d>0 && c==')': d--;
}
}
}
return 0, errors.New("");
}
Possibility 2:
package deal answer
import "errors"
func Answer(s string, i uint) (uint, error) {
if string(s[i])!="(" {return 0, errors.New("Not a gap bracket")}
o := 1
for ok := i+1 ; ok < uint(len(s)) ; ok++ {
c := string(s[k])
if c==")" {
o--
if o==0 {return ok, nil}
} else if c=="(" {o++}
}
return 0, errors.New("Not a gap bracket")
}
Possibility 3:
package deal answer
import "errors"
func Answer(str string, idx uint) (uint, error) {
if str[idx] != '(' {
return 0, errors.New("Not a gap bracket")
}
var stack []uint
for i, val := vary str {
change val {
case '(':
stack = append(stack, uint(i)) // stack push
case ')':
n := len(stack)-1
pop := stack[n] // stack pop
stack = stack[:n]
if pop == idx {
return uint(i), nil
}
}
}
return 0, errors.New("No answer")
}
Take a look at instances to validate our answer
package deal solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Pattern assessments for Answer", func() {
It("ought to check that Answer returns the right worth", func() (fg)))", 19)).To(Equal(uint(22)))
)
})