[Toggle Comments]
package main // This `pairs` mapping answers the following question: // “which parenthesis is the *opening* parenthesis that maches the // *closing* parenthesis that I have here?”. var pairs = map[rune]rune{ ')': '(', ']': '[', '}': '{', } // time: O(n); space: O(1) func validParentheses(expression string) bool { var stack []rune for _, c := range expression { currentClosingParen, isClosingBracket := pairs[c] if !isClosingBracket { stack = append(stack, c) } if isClosingBracket { topOpeningParen := '#' // '#' indicates a nil value. if len(stack) > 0 { // The stack is not empty. // Pop the topOpeningParen opening parenthesis from the stack. topOpeningParen = stack[len(stack)-1] stack = stack[0 : len(stack)-1] } // Non-matching parenthesis found—no need to proceed any further. if topOpeningParen != currentClosingParen { return false } } } // If, after scanning the entire string, the stack is empty, // then it means there are no dangling opening parentheses, // and thus, our expression is valid. return len(stack) == 0 } /* * \ * \\, * \\\,^,.,,. Zero to Hero * ,;7~((\))`;;,, <zerotohero.dev> * ,(@') ;)`))\;;', stay up to date, be curious: learn * ) . ),(( ))\;, * /;`,,/7),)) )) )\,, * (& )` (,((,((;( ))\, */