Skip to content

Instantly share code, notes, and snippets.

@halilb
Last active May 20, 2016 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halilb/67efb7eae92433a2ec5b7df0789bfa14 to your computer and use it in GitHub Desktop.
Save halilb/67efb7eae92433a2ec5b7df0789bfa14 to your computer and use it in GitHub Desktop.
/*
* 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