Last active
May 20, 2016 14:53
-
-
Save halilb/67efb7eae92433a2ec5b7df0789bfa14 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
* Description: | |
* validBraces takes a string of braces, | |
* and determines if the order of the braces is valid. | |
* validBraces should return true if the string is valid, | |
* and false if it's invalid. | |
* | |
* Test Cases: | |
* validBraces( "(){}[]" ) => returns true | |
* validBraces( "(}" ) => returns false | |
* validBraces( "[(])" ) => returns false | |
* validBraces( "([{}])" ) => returns true | |
*/ | |
const BRACES = { | |
'{': '}', | |
'[': ']', | |
'(': ')', | |
}; | |
function validBraces(braces) { | |
const stack = []; | |
let isValid = true; | |
for (let i = 0, len = braces.length; i < len; i++) { | |
const brace = braces[i]; | |
// if it's an opening brace | |
if (BRACES[brace]) { | |
stack.push(brace); | |
} else { // if it's a closing brace | |
const lastOpeningBrace = stack.pop(); | |
// this string is not valid | |
// when current brace is a closing brace | |
// but not for the last opening brace | |
if (BRACES[lastOpeningBrace] !== brace) { | |
isValid = false; | |
break; | |
} | |
} | |
} | |
return isValid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment