Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Valid Parentheses

Posted on January 11, 2018July 26, 2020 by braindenny

Valid Parentheses



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #parentheses, #string

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

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/valid-parentheses
// Basic Ideas: stack
// Complexity: Time O(n), Space O(n)
func isValid(s string) bool {
    stack := []byte{}
    m := map[byte]byte{')':'(', ']':'[', '}':'{'}
    for i, _ := range s {
        ch := byte(s[i])
        if _, ok := m[ch]; ok {
            if len(stack)<1 || stack[len(stack)-1] != m[ch] {
                return false
            }
            stack = stack[0:len(stack)-1]
        } else {
            stack = append(stack, ch)
        }
    }
    return len(stack) == 0
}
linkedin
github
slack

Post Views: 8
Posted in BasicTagged #parentheses, #stack

Post navigation

LeetCode: Sum of Two Integers
LeetCode: Binary Tree Level Order Traversal

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.