LeetCode 算法题【Easy】:20. Valid Parentheses

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

Question

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.
  3. Every close bracket has a corresponding open bracket of the same type.

Example 1:

1
2
Input: s = "()"
Output: true

Example 2:

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

Example 3:

1
2
Input: s = "(]"
Output: false

My Answer

1
2
3
4
5
6
7
8
9
var isValid = function(s) {
const strCount = s.length
if (strCount % 2 === 1) return false
let tempStr = s
while(tempStr.includes('[]') || tempStr.includes('{}') || tempStr.includes('()')) {
tempStr = tempStr.replace('[]', '').replace('{}', '').replace('()', '')
}
return tempStr === ''
};

My Answer’s Performance

6