0ms golang solution. Just an easy example to realize Stack.


  • 0
    X
    import (
    	"errors"
    )
    
    type Stack struct {
    	values []string
    	StackInterface
    }
    
    type StackInterface interface {
    	empty() bool
    	pop() (string, error)
    	push(element string)
    }
    
    func (stack *Stack) empty() bool {
    	return len(stack.values) == 0
    }
    
    func (stack *Stack) pop() (str string, e error) {
    	if stack.empty() {
    		return "", errors.New("Stack is empty!")
    	}
    	val := stack.values[len(stack.values)-1]
    	stack.values = stack.values[:len(stack.values)-1]
    	return val, nil
    }
    
    func (stack *Stack) push(element string) {
    	stack.values = append(stack.values, element)
    }
    
    func isValid(s string) bool {
    	stack := Stack{}
    	parentheses_map := map[string]string{")": "(", "}": "{", "]": "["}
    	for i := 0; i < len(s); i++ {
    		character := string(s[i])
    		if character == "(" || character == "{" || character == "[" {
    			stack.push(character)
    		}
    		if character == ")" || character == "}" || character == "]" {
    			val, err := stack.pop()
    
    			if err != nil {
    				return false
    			}
    			if val != parentheses_map[character] {
    				return false
    			}
    		}
    	}
    	if stack.empty() {
    		return true
    	}
    	return false
    
    }
    

Log in to reply
 

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