Javascript Algorithm String Parenthesis match

Description

Javascript Algorithm String Parenthesis match


function Stack(array) {
    this.array = [];/*from w w  w  .  j  a  va 2s .com*/
    if (array) this.array = array;
}

Stack.prototype.getBuffer = function() {
    return this.array.slice();
}

Stack.prototype.isEmpty = function() {
    return this.array.length == 0;
}

Stack.prototype.peek = function() {
    return this.array[this.array.length - 1];
}


Stack.prototype.push = function(value) {
    this.array.push(value);
}


Stack.prototype.pop = function() {
    return this.array.pop();
};

function isParenthesisValid(validationString) {
    var stack = new Stack();
    for (var pos = 0; pos < validationString.length; pos++) {
        var currentChar = validationString.charAt(pos);
        if (currentChar == "(") {
            stack.push(currentChar);
        } else if (currentChar == ")") {

            if (stack.isEmpty())
                return false;

            stack.pop();
        }
    }
    return stack.isEmpty();
}
let a = isParenthesisValid("((()"); // false;
console.log(a);
a = isParenthesisValid("(((("); // false;
console.log(a);
a = isParenthesisValid("()()"); // true;
console.log(a);



PreviousNext

Related