Brackets
by krustnic
HTML
<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>
JavaScript
class Stack {
constructor() {
this._data = [];
}
push (v) {
this._data.push(v);
}
pop (v) {
return this._data.pop();
}
size () {
return this._data.length;
}
}
function isClosing(s) {
if (s === '}') return true;
return false;
}
function isValid(exp) {
const stack = new Stack();
for(let i=0; i<exp.length; i++) {
const c = exp[i];
if (!isClosing(c)) {
stack.push(c);
} else {
const v = stack.pop()
if (v === undefined) return false;
}
}
if (stack.size() !== 0) {
return false;
}
// console.log(exp);
return true
}
console.log(isValid("{{}"));
console.log(isValid("}"));
console.log(isValid("}{"));
console.log(isValid("{{{}{}{{}}}}"));