Created
March 2, 2019 13:29
-
-
Save iuliaL/8f0589418ac1e4c4d7cd48d2cd3202d1 to your computer and use it in GitHub Desktop.
Is matching brackets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isMatchingBrackets(str) { | |
let stack = []; | |
const map = { | |
'(': ')', | |
'[': ']', | |
'{': '}' | |
}; | |
let answer = false; | |
for (let c of [...str]) { | |
if (Object.keys(map).includes(c)) { | |
// is opening | |
stack.push(c); | |
} else { | |
// if it's closing type | |
// check if stack is empty | |
if (stack.length === 0) { | |
// i return false because stack is empty and i want to break out of the loop | |
answer = false | |
break; | |
} else { | |
const lastOpen = stack.pop() // has to be ( { [ | |
const match = map[lastOpen] === c; | |
if (match) { | |
// i have a match (this closing has an opening as the last item in stack | |
answer = true; | |
} else { | |
// i dont have a match | |
answer = false; | |
} | |
} | |
} | |
} | |
if (stack.length) { | |
answer = false | |
} | |
return answer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment