Skip to content

Instantly share code, notes, and snippets.

@remarkablemark
Created November 9, 2024 19:55
Show Gist options
  • Save remarkablemark/1c79a5137cc267c839bb8f74d55ab2c6 to your computer and use it in GitHub Desktop.
Save remarkablemark/1c79a5137cc267c839bb8f74d55ab2c6 to your computer and use it in GitHub Desktop.
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