LeetCode-20. 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.

Constraints:

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

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @param {string} s
* @return {boolean}
*/
const isValid = function (s) {
let stack = []
let dict = {
'(': ')',
'[': ']',
'{': '}'
}

for (let i = 0; i < s.length; i++) {
if (dict[s[i]] !== undefined) {
stack.push(dict(s[i]))
} else if (s[i] !== stack.pop()) {
return false
}
}
return stack.length === 0
}