分享一段代码片段:判断一段字符串中的括号是否正确配对

package main

import "fmt"

func main() {
    // 判断一段字符串中的括号是否正确成对,以下是5个测试字符串
    teststr1 := "(a(b(c)))"
    fmt.Printf("teststr1:%v\n", determine(teststr1))
    teststr2 := "(a(bqweqw(zxcxzc)s(a)d(c)qweweq()))"
    fmt.Printf("teststr1:%v\n", determine(teststr2))
    teststr3 := "(q(weu((qw(ja(sk()(d)a)k)))shda)skhd"
    fmt.Printf("teststr1:%v\n", determine(teststr3))
    teststr4 := "))(q(weu((qw(ja(sk()(d)a)k)))shda)skhd"
    fmt.Printf("teststr1:%v\n", determine(teststr4))
    teststr5 := "ll)(q(weu((qw(ja(sk()(d)a)k)))shda)skhd"
    fmt.Printf("teststr1:%v\n", determine(teststr5))
}

func determine(str string) bool {
    var sl []string
    for _, c := range str {
        if string(c) == "(" || string(c) == ")" {
            sl = append(sl, string(c))
        }
    }
    for i := 0; i < len(sl); i++ {
        if i == 0 && sl[i] == ")" {
            return false
        }
        if sl[i] == "(" {
            continue
        } else {
            sl = append(sl[:i-1], sl[i+1:]...)
            i = 0
        }
    }
    if len(sl) == 0 {
        return true
    }
    return false
}

你可能感兴趣的:(分享一段代码片段:判断一段字符串中的括号是否正确配对)