/**
* @param {string} str
* @return {boolean}
*/
const isValid = function(str) {
/*
if (typeof str !== 'string') {
return false;
}
*/
const stack = [];
const map = {
')': '(',
'}': '{',
']': '['
};
for (const char of str) {
if (Object.values(map).includes(char)) {
stack.push(char);
} else if (Object.keys(map).includes(char)) {
if (map[char] !== stack[stack.length - 1]) {
return false;
}
stack.pop();
}
}
return stack.length === 0;
};
console.log(
isValid('{{[test]})'), // false
isValid('({[test]})'), // true
isValid('({['), // false
isValid(''), // true
);
/* You can verify the following cases as well, by uncommenting the if statement at the start of the method.
console.log(
isValid(), // false
isValid(null), // false
isValid(0), // false
isValid(1), // false
isValid(1.12) // false
);
*/
Categories