Golang solution (0ms) using slice as stack


  • 0

    Since the Go standard library does not come with a stack data structure (unlike Java/C++/Python etc), we use slices to simulate stacks.

    func isValid(s string) bool {
        stack := []byte{}
        for i := 0; i < len(s); i++ {
            b := s[i]
            if b == '{' || b == '[' || b == '(' {
                stack = append(stack, b)          // Push
                continue
            }
            if len(stack) == 0 { return false }   // Check if the stack is empty
            top := stack[len(stack) - 1]          // Peek the top of the stack
            switch b {
            case '}':
                if top != '{' { return false }
            case ']':
                if top != '[' { return false }
            case ')':
                if top != '(' { return false }
            default:
                // If the input character/byte is invalid i.e not equal to "{}[]()", return false.
                return false
            }
            stack = stack[:len(stack) - 1]        // Pop
        }
        return len(stack) == 0
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.