Skip to content

Instantly share code, notes, and snippets.

@condef5
Last active January 22, 2019 12:54
Show Gist options
  • Select an option

  • Save condef5/33e297b41c1b0a609a2b822bbb390715 to your computer and use it in GitHub Desktop.

Select an option

Save condef5/33e297b41c1b0a609a2b822bbb390715 to your computer and use it in GitHub Desktop.
// solution with functional programming
function validParentheses(cad) {
if (cad.length === 0) {
return true;
}
if (cad[0] === ')' || cad[cad.length - 1] === '(') {
return false;
} else {
if (cad[1] === ')') {
return validParentheses(cad.slice(2));
} else {
var index = cad.indexOf(')');
return validParentheses(cad.slice(0, index - 1) + cad.slice(index + 1));
}
}
}
// solution initial
function validParentheses(cad) {
let arr = cad.split('');
while (arr.length !== 0) {
let band = true;
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] === '(' && arr[i + 1] === ')') {
arr.splice(i, 2);
band = false;
break;
}
}
if (band) break;
}
return arr.length === 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment