Last active
April 8, 2021 06:23
-
-
Save fanatikhamsi/f3d8b778bd02448bbd40fdf9d7e40684 to your computer and use it in GitHub Desktop.
Stack of characters in JS
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
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