Faaez Razeen

Valid Parentheses

  • 1 min read
  • Stack
  • String
  • LC-Easy
  • Blind75

3 years ago

Approach: Stack

We can use a stack to keep track of the opening brackets. When we encounter a closing bracket, we check if the top of the stack is the corresponding opening bracket. If it is, we pop the stack. If it isn't, we return false. If we reach the end of the string and the stack is empty, we return true. Otherwise, we return false.

def isValid(s: str) -> bool: stack = [] mapping = {'(': ')', '{': '}', '[': ']'} for ch in s: if ch in mapping: stack.append(ch) elif len(stack) == 0 or mapping[stack.pop()] != ch: return False return len(stack) == 0