Solution Review: Check Parentheses
This lesson will discuss the two possible solutions to the challenge in the previous lesson.
Solution 1 #
Press + to interact
function balancedParentheses(str) {let stack = [];let map = {'(': ')','[': ']','{': '}'}for (let i = 0; i < str.length; i++) {// If character is an opening brace add it to a stackif (str[i] === '(' || str[i] === '{' || str[i] === '[' ) {stack.push(str[i]);}//if closing brace, pop from stackelse {let lastEle = stack.pop();//Return false if the element popped doesn’t match the corresponding closing brace in the mapif (str[i] !== map[lastEle]) {return false};}}//if stack not empty at end, return falseif (stack.length !== 0) {return false};return true;}console.log(balancedParentheses("{[]()}" ));console.log(balancedParentheses("{[(])}"));console.log(balancedParentheses("{[}"));
Explanation #
Checking for balanced parentheses is a classic problem that is asked during interviews. The ...
Access this course and 1400+ top-rated courses and projects.