Created
November 9, 2024 19:55
-
-
Save remarkablemark/1c79a5137cc267c839bb8f74d55ab2c6 to your computer and use it in GitHub Desktop.
Valid parentheses: https://leetcode.com/problems/valid-parentheses/description/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const REGEX = /\(\)|\{\}|\[\]/g; | |
/** | |
* 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. | |
* | |
* Examples: | |
* - "()" => Valid | |
* - "()[]{}" => Valid | |
* - "(]" => Invalid | |
* - "([)]" => Invalid"))" | |
* | |
* @param {string} string | |
* @returns {boolean} | |
*/ | |
function isValidParentheses(string) { | |
while (REGEX.test(string)) { | |
string = string.replace(REGEX, ''); | |
} | |
return !string.length; | |
} | |
console.assert(isValidParentheses('()')); | |
console.assert(isValidParentheses('(){}')); | |
console.assert(isValidParentheses('(){}[]')); | |
console.assert(isValidParentheses('(){}[]')); | |
console.assert(isValidParentheses('([{}])')); | |
console.assert(isValidParentheses('([{{}}])')); | |
// console.assert(isValidParentheses('([{}]))')); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment