matchingbrackets js

Solutions on MaxInterview for matchingbrackets js by the best coders in the world

showing results for - "matchingbrackets js"
Lindsay
01 May 2017
1sMatchingBrackets = function(str) {
2    let stack = [];
3    let map = {
4        '(': ')',
5        '[': ']',
6        '{': '}'
7    }
8    for (let i = 0; i < str.length; i++) {
9        // If character is an opening brace add it to a stack
10        if (str[i] === '(' || str[i] === '{' || str[i] === '[') {
11            stack.push(str[i]);
12        }
13        //  If that character is a closing brace, pop from the stack, 
14       // which will also reduce the length of the stack each time a closing bracket is encountered.
15        else {
16            let last = stack.pop();
17            //If the popped element from the stack, which is the last opening brace 
18           // doesn’t match the corresponding closing brace in the map, then return false
19            if (str[i] !== map[last]) {
20                return false
21            };
22        }
23    }
24    // By the completion of the for loop after checking all the brackets of 
25   // the str, at the end, if the stack is not empty then fail
26    if (stack.length !== 0) {
27        return false
28    };
29    return true;
30}
31console.log(isMatchingBrackets("(){}")); // returns true
32console.log(isMatchingBrackets("[{()()}({[]})]({}[({})])((((((()[])){}))[]{{{({({({{{{{{}}}}}})})})}}}))[][][]")); 
33// returns true
34
35console.log(isMatchingBrackets("({(()))}}")); // returns false
36
similar questions
queries leading to this page
matchingbrackets js