有效括号问题索引超出范围(Go)

我正在将以前在 Python 中解决的问题的代码转换为 Go 并遇到运行时错误:索引超出范围 [1],此行中的长度为 1


 if string(s[i]) == ")" && arr[len(s) - 1] == "("{

这是完整的代码。


func isValid(s string) bool {

    arr := make([]string, 0)

    if len(s) < 2 {

        return false 

    }


    for i := 0; i < len(s); i++ {


        if string(s[i]) == "(" || string(s[i]) == "[" || string(s[i]) == "{" {

            arr = append(arr, string(s[i]))

        } else if string(s[i]) == ")" || string(s[i]) == "]" || string(s[i]) == "}" {

            if len(arr) >= 1 { 

                if string(s[i]) == ")" && arr[len(s) - 1] == "("{ 

                    arr = arr[:len(arr) -1]

                } else if string(s[i]) == "]" && arr[len(s) - 1] == "[" {

                    arr = arr[:len(arr) -1]

                } else if string(s[i]) == "}" && arr[len(s) - 1] == "{" {

                    arr = arr[:len(arr) -1]

                }  else {

                    return false

                }

            }else {

                return false

            }

    }

    }

    if reflect.DeepEqual(arr, []string{""}) {

        return true

    } else  {

        return false

    }

    

}


问题的原因是什么?


繁花不似锦
浏览 169回答 1
1回答

开满天机

您曾经len(s)-1找到 的最后一个索引arr,但它应该是len(arr)-1。这是您的代码的工作版本,它修复了一些额外的错误,并避免了对单个字符的不必要的字符串转换。https://go.dev/play/p/sazf2RguoIrpackage mainimport "fmt"func isValid(s string) bool {&nbsp; &nbsp; var arr []rune&nbsp; &nbsp; for _, c := range s {&nbsp; &nbsp; &nbsp; &nbsp; if c == '(' || c == '[' || c == '{' {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr = append(arr, c)&nbsp; &nbsp; &nbsp; &nbsp; } else if c == ')' || c == ']' || c == '}' {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if len(arr) == 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var last rune&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr, last = arr[:len(arr)-1], arr[len(arr)-1]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if c == ')' && last != '(' || c == ']' && last != '[' || c == '}' && last != '{' {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return len(arr) == 0}func main() {&nbsp; &nbsp; cases := []string{&nbsp; &nbsp; &nbsp; &nbsp; "()[({}())]",&nbsp; &nbsp; &nbsp; &nbsp; "(]",&nbsp; &nbsp; &nbsp; &nbsp; "((())",&nbsp; &nbsp; &nbsp; &nbsp; "{{{}}}",&nbsp; &nbsp; &nbsp; &nbsp; "{{{[][][]}}}",&nbsp; &nbsp; }&nbsp; &nbsp; for _, c := range cases {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(c, isValid(c))&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go