Please review my balanced parenthesis string checker
code below.
I would love to know how to improve my algorithm and if you have any other feedback.
// comments inline
function validateParenthesisString(inputString){
if(inputString.length === 0){ // empty string is as good as a valid string
console.log('String is valid.');
return;
}
var element,
parenthesisStack = [];
// iterate through the string
for(var index = 0, length = inputString.length; index < length; index++){
element = inputString.charAt(index); // cache the character
switch(element){
case '(':
parenthesisStack.push('('); // openeing bracket, so just push it
break;
case ')':
if(parenthesisStack[parenthesisStack.length-1] === '('){ // check if corresponding counterpart pushed already
parenthesisStack.pop(); // remove
} else {
parenthesisStack.push(')');
}
break;
case '[':
parenthesisStack.push('[');
break;
case ']':
if(parenthesisStack[parenthesisStack.length-1] === '['){
parenthesisStack.pop();
} else {
parenthesisStack.push(']');
}
break;
case '{':
parenthesisStack.push('{');
break;
case '}':
if(parenthesisStack[parenthesisStack.length-1] === '{'){
parenthesisStack.pop();
} else {
parenthesisStack.push('}');
}
break;
default: // garbage character
console.log('Invalid character encountered: ' + inputString.charAt(index));
console.log('Please enter a valid string.');
console.log('parenthesisStack:', parenthesisStack);
console.log('***********************************');
return;
};
}
console.log('parenthesisStack:', parenthesisStack); // just for debugging
// check parenthesisStack
if(parenthesisStack.length === 0){
console.log('String is valid!');
} else {
console.log('String is invalid!');
}
console.log('***********************************');
};
validateParenthesisString('test'); // invalid
validateParenthesisString('({)}[()]{'); // invalid
validateParenthesisString('[({})]{}'); // valid