Last active
December 5, 2021 09:03
-
-
Save segaz2002/7aeaae4474e19a8af9988dc377b54eee to your computer and use it in GitHub Desktop.
Balanced Brackets Problem - Hackerrank
This file contains hidden or 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 Node(data) { | |
this.data = data; | |
this.next = null; | |
} | |
function Stack() { | |
this.top = null; | |
} | |
Stack.prototype.push = function(data){ | |
let node = new Node(data); | |
if(this.top == null){ | |
this.top = node; | |
return; | |
} | |
node.next = this.top; | |
this.top = node; | |
return; | |
} | |
Stack.prototype.pop = function(){ | |
if(this.top == null) return; | |
let data = this.top.data; | |
this.top = this.top.next; | |
return data; | |
} | |
Stack.prototype.empty = function(){ | |
return this.top == null; | |
} | |
function isBalanced(s) { | |
let pairs = {"}": "{", "]": "[", ")": "("}; | |
let res = new Stack() | |
for(let i=0; i <= s.length -1; i++){ | |
if(pairs[(s[i])]){ | |
let popped = res.pop(); | |
if (pairs[s[i]] != popped) return "NO"; | |
}else{ | |
res.push(s[i]); | |
} | |
} | |
return (res.empty()) ? "YES" : "NO"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment