golang problem solving standard bracket problem

Posted May 28, 20201 min read

· https://github.com/azl3979858...

package main

import "container/list"
import "fmt"

func main(){
    s := "{{}}"
    m := "{{[()}]}"
    l := "{[(())]}"

    fmt.Println(check(s))
    fmt.Println(check(m))
    fmt.Println(check(l))
}

func check(x string) bool {

    mapper := map[byte]byte{
        '{':'}',
        '(':')',
        '[':']',
    }

    stack := list.New() //  

    for _, v := range x {
        i := byte(v)
        if _, ok := mapper[i]; ok {
            //
            stack.PushFront(i)
            fmt.Println(i)
        } else {
            if stack.Len() == 0 {
                return false
            }
            l := stack.Remove(stack.Front()).(byte)
            r, ok := mapper[l]
            if !ok || r != i {
                return false
            }
            fmt.Printf("%s:%s", "S", string(i))
            fmt.Printf("%s:%s", "L", string(l))
            fmt.Printf("%s:%s", "R", string(r))
            fmt.Println()
        }
    }
    if stack.Len() > 0 {
        return false
    }
    return true
}