Leetcode 20. Valid Parentheses

Gary Chiang
Aug 16, 2021

[easy]

https://leetcode.com/problems/valid-parentheses/

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:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

Example 4:

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

Example 5:

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

[Java]

  1. Using stack to solve this leetcode. If we find the open parentheses, we push them into the stack; if we find the close parentheses, we peek the stack, and if it’s a match, pop from the stack.
  2. return false if something else appear in the string, or return true in the end.

--

--

Gary Chiang

CS new grad, 6 years experience related to supply chain management. Located in Bay area