Skip to content
the poor coder

Leetcode - Valid Parentheses Solution

Poor Man
Published
Updated
Reading time
1 min read

Given a string s 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.

Example 1:

Text
Input: s = "()"
Output: true

Example 2:

Text
Input: s = "()[]{}"
Output: true

Example 3:

Text
Input: s = "(]"
Output: false

Example 4:

Text
Input: s = "([)]"
Output: false

Example 5:

Text
Input: s = "{[]}"
Output: true

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

Solution in Python#

Python
import re
class Solution:
    def isValid(self, s: str) -> bool:
        bracket_map = {"(": ")", "[": "]",  "{": "}"}
        open_par = set(["(", "[", "{"])
        stack = []
        for i in s:
            if i in open_par:
                stack.append(i)
            elif stack and i == bracket_map[stack[-1]]:
                stack.pop()
            else:
                return False
        return stack == []

Keep going

2021

Leetcode - Make The String Great Solution

Given a string s of lower and upper case English letters. A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: 0 <= i <= s.length - 2 s[i] is a lower-case letter and s[i + 1] is…

2021

Leetcode - Camelcase Matching Solution

A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query. (We may insert each character at any position, and may insert 0 characters.) Given a list of…

ESC