Wednesday, May 31, 2023
HomeSoftware EngineeringReturn Index of Matching Closing Bracket in Go

# Return Index of Matching Closing Bracket in Go

## The problem#

On this problem, you can be given a string with brackets and an index of a gap bracket and your process will probably 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 a reply.

Examples:

``````resolve("((1)23(45))(aB)", 0) = 10 // the opening brace at index 0 matches the closing brace at index 10
resolve("((1)23(45))(aB)", 1) = 3
resolve("((1)23(45))(aB)", 2) = -1 // there isn't a opening bracket at index 2, so return -1
resolve("((1)23(45))(aB)", 6) = 9
resolve("((1)23(45))(aB)", 11) = 14
resolve("((>)|?(*'))(yZ)", 11) = 14
``````

Enter will encompass letters, numbers, and particular characters, however no areas. The one brackets will probably be `(` and `)`.

Possibility 1:

``````bundle 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];
swap {
case d==0 && c==')': return j, nil;
case c=='(': d++;
case d>0 && c==')': d--;
}
}
}
return 0, errors.New("");
}
``````

Possibility 2:

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

``````bundle 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 {
swap 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
}
}
}

}
``````

## Check circumstances to validate our answer#

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