GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/20.Valid Parentheses at master · geemo/leetcode

Expand file tree

/

20.Valid Parentheses

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
/

20.Valid Parentheses

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
README.md
README.md
 
 

README.md

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: false

Example 3:

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

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true 

Solution:

func isValid(s string) bool {
	if s == "" {
		return true
	}

	str := []byte(s)
	chMap := map[byte]byte{'{': '}', '(': ')', '[': ']'}
	var stack []byte
	for _, ch := range str {
		// push ch onto stack when that is one of the left parentheses
		if _, ok := chMap[ch]; ok {
			stack = append(stack, ch)
			continue
		}
		// pop top of stack if not 
		stackTopIdx := len(stack) - 1
		if stackTopIdx < 0 {
			return false
		}
		stackTop := stack[stackTopIdx]
		if chMap[stackTop] != ch {
			return false
		}
		stack = stack[:stackTopIdx]	
	}
	
	if len(stack) != 0 {
		return false
	}

	return true
}
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.