Created
February 13, 2018 21:32
-
-
Save janetlee/b8d3b099904a4383fc7b342b553b6fef to your computer and use it in GitHub Desktop.
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 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