Balanced Brackets

要效率的话用arr 代替stack

package main

import (
    "fmt"
)

func main(){
    var num int
    fmt.Scanln(&num)

    f := func(t []byte) bool {
        h := make([]byte, len(t))
        var top int
        for _, v := range t {
            switch v {
            case '{', '[', '(':
                h[top] = v
                top++
            case ')', ']', '}':
                if top-1 < 0 {
                    return false
                }
                if v == ')' && h[top-1] != '(' {
                    return false
                } else if v == ']' && h[top-1] != '[' {
                    return false
                } else if v == '}' && h[top-1] != '{' {
                    return false
                }
                top--
            }
        }
        if top == 0{
            return true
        }
        return false
    }
    result := make([]bool, 0, num)
    for i := 0; i < num; i++ {
        var t string
        fmt.Scanln(&t)
        result = append(result, f([]byte(t)))
    }                                                                                                                                                                                                                   
     for _, val := range result {
        if val == true {
            fmt.Println("YES")
        } else {
            fmt.Println("NO")
        }
    }
}
    
 

你可能感兴趣的:(Balanced Brackets)