The task is to determine the validity of a pair of parentheses, brackets or braces
function validate(str) {
// your code here
}
Use a stack to keep track of opening symbols
const stack = [];
const pairs = {
")":"(",
"]": "[",
"}": "{"
}
Each time you see an opening bracket, brace or parenthesis, push it into the stack
for (let char of str) {
if(char === "(" || char === "[" || char === "{") {
stack.push(char);
}
}
Each time you see a closing bracket, brace or parenthesis, check if the top of the stack matches
else if ( char === ")" || char === "]" || char === "}") {
if(stack.pop() !== pairs[char]) {
return false;
}
}
If the stack is empty at the end, the string is valid
return stack.length === 0
The final code
function validate(str) {
// your code here
const stack = [];
const pairs = {
")":"(",
"]": "[",
"}": "{"
}
for (let char of str) {
if(char === "(" || char === "[" || char === "{") {
stack.push(char);
} else if ( char === ")" || char === "]" || char === "}") {
if(stack.pop() !== pairs[char]) {
return false;
}
}
}
return stack.length === 0;
}
That's all folks!
Top comments (0)