Skip to content

Instantly share code, notes, and snippets.

@segaz2002
Last active December 5, 2021 09:03
Show Gist options
  • Save segaz2002/7aeaae4474e19a8af9988dc377b54eee to your computer and use it in GitHub Desktop.
Save segaz2002/7aeaae4474e19a8af9988dc377b54eee to your computer and use it in GitHub Desktop.
Balanced Brackets Problem - Hackerrank
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