Skip to content

Instantly share code, notes, and snippets.

@janetlee
Created February 13, 2018 21:32
Show Gist options
  • Save janetlee/b8d3b099904a4383fc7b342b553b6fef to your computer and use it in GitHub Desktop.
Save janetlee/b8d3b099904a4383fc7b342b553b6fef to your computer and use it in GitHub Desktop.
function isLeft(char) {
return (char === "(" || char === "[" || char === "{") ? true : false;
}
function isValidPair(str) {
str.split("");
var stack =[];
var pairs = {")": "(", "]": "[", "}": "{"};
if (str.length <= 1) {
return false;
}
for (var i =0; i < str.length; i++) {
if (isLeft(str[i])) {
stack.push(str[i]);
} else {
if (pairs[str[i]] === stack[stack.length -1]) {
stack.pop();
} else {
return false;
}
}
}
if (stack.length !== 0) {
return false;
}
return true;
}
console.log(isValidPair("()[{}]"));
console.log(isValidPair("{[}]"));
console.log(isValidPair("{()"));
console.log(isValidPair("{("));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment