# Return Index of Matching Closing Bracket in Go

0
9

## The problem#

On this problem, you may be given a string with brackets and an index of a gap bracket and your job can be to return the index of the matching closing bracket. Each the enter and returned index are 0-based. A gap brace will all the time have a closing brace. Return an error if there isn’t a 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 a 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 include letters, numbers, and particular characters, however no areas. The one brackets can be `(` and `)`.

Possibility 1:

``````bundle resolution;
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:

``````bundle resolution

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 okay := i+1 ; okay < uint(len(s)) ; okay++ {
c := string(s[k])
if c==")" {
o--
if o==0 {return okay, nil}
} else if c=="(" {o++}
}
return 0, errors.New("Not a gap bracket")
}
``````

Possibility 3:

``````bundle resolution

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 resolution")
}
``````

## Take a look at instances to validate our resolution#

``````bundle solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Pattern exams for Answer", func() {
It("ought to take a look at that Answer returns the right worth", func() (fg)))", 19)).To(Equal(uint(22)))
)
})
``````