Created
October 27, 2020 01:45
-
-
Save TechWithTy/fe587c42469356d008e324379fd55aa3 to your computer and use it in GitHub Desktop.
Valid Parenthesis LeetCode Algorithim
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
// /** | |
// * @param {string} s | |
// * @return {boolean} | |
// */ | |
let brackets = { | |
"(": ")", | |
"[": "]", | |
"{": "}", | |
}; | |
var isValid = function(s) { | |
let stack = []; | |
for (let i = 0; i < s.length; i++) { | |
let currentParen = s[i]; | |
let closingParen = brackets[currentParen]; | |
if (closingParen) stack.push(closingParen); | |
else if (currentParen !== stack.pop()) return false; | |
} | |
return !stack.length; // true when stack is empty, false otherwise | |
}; | |
/* 1- Create Object to reference closing parenthesis | |
2- Create Stack for closing parens | |
3- loop through array | |
4- set variable for current paren | |
5-set variable for closed paren | |
6- if closing paren exists push it onto stack | |
7-if not and current value does not equal value in stack return false; | |
8- if stack is empty return true otherwise return false | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment