Skip to content

Instantly share code, notes, and snippets.

@fanatikhamsi
Last active April 8, 2021 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fanatikhamsi/f3d8b778bd02448bbd40fdf9d7e40684 to your computer and use it in GitHub Desktop.
Save fanatikhamsi/f3d8b778bd02448bbd40fdf9d7e40684 to your computer and use it in GitHub Desktop.
Stack of characters in JS
class Stack {
constructor() {
this.items = [];
this.top = null;
}
getTop() {
if (this.items.length == 0)
return null;
return this.top;
}
isEmpty() {
return this.items.length == 0;
}
size() {
return this.items.length;
}
push(element) {
this.items.push(element);
this.top = element;
}
pop() {
if (this.items.length != 0) {
if (this.items.length == 1) {
this.top = null;
return this.items.pop();
} else {
this.top = this.items[this.items.length - 2];
return this.items.pop();
}
} else
return null;
}
}
function isBalanced(exp) {
var myStack = new Stack();
for (var i = 0; i < exp.length; i++) {
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') {
if (myStack.isEmpty()) {
return false
}
let output = myStack.pop();
if (((exp[i] == "}") && (output != "{")) || ((exp[i] == ")") && (output != "(")) || ((exp[i] == "]") && (output != "["))) {
return false;
}
} else {
myStack.push(exp[i]);
}
}
if (myStack.isEmpty() == false) {
return false
}
return true
}
var inputString = "{[()]}"
console.log(inputString)
console.log(isBalanced(inputString))
inputString = "{[([({))]}}"
console.log(inputString)
console.log(isBalanced(inputString))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment