[Go] LeetCode 20. Valid Parentheses

TAKASHI NARIKAWA
Jan 21 · 1 min read

Description

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

Solution

/* Approach 1: Stacks */
func makeParMap() map[string]string{
parMap := make(map[string]string)
parMap["}"] = "{"
parMap["]"] = "["
parMap[")"] = "("
return parMap
}
func isValid(s string) bool {
var stack []string
for i := 0; i < len(s); i++{
char := string(s[i])
parMap := makeParMap()
if _,ok := parMap[char]; ok{
if len(stack) == 0 {
return false
}
n := len(stack)-1
pop := stack[n]
if parMap[char] != pop{
return false
}
//pop
stack = stack[:n]
continue
}
//push
stack = append(stack,char)
}
return len(stack) == 0
}

repo: https://github.com/fukubaka0825/LeetCodeInGo/blob/master/Algorithms/0020.valid_parentheses/valid_paretheses.go

TAKASHI NARIKAWA

Written by

Web developer in Tokyo. SRE/devops/Go/AWS/Terraform

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade