"Clean code always looks like it was written by someone who cares."
/**
* @param {string} s
* @returns {boolean}
*/
var isValid = function(s) {
if ((s.length % 2 === 1) || (s.length === 0)) {
return false;
}
var brackets = [],
openBracketsMapping = {
'(': ')',
'[': ']',
'{': '}'
},
chars = s.split(''),
currentChar = '',
couple = '';
for (var i = 0; i < chars.length; i++) {
currentChar = chars[i];
if (currentChar in openBracketsMapping) {
brackets.push(currentChar);
} else {
if (openBracketsMapping[brackets.pop()] !== currentChar) {
return false;
} else {
continue;;
}
}
}
if (brackets.length === 0) {
return true;
}
return false;
};
/**
* @param {string} s
* @returns {boolean}
*/
var openBracketMapping = {
'(': ')',
'[': ']',
'{': '}'
};
var bracketStack;
var isValid = function(s) {
if (isImpossibleValid(s)) {
return false;
}
return isValidCheck(s);
};
function isValidCheck(s) {
initBracketStack();
var chars = s.split('');
for(var i = 0; i < chars.length; i++) {
var c = chars[i];
if (isOpenBracket(c)) {
getNewOpenBracket(c);
} else if (!isCorrectCloseBracket(c)) {
return false;
}
}
return isBracketStackEmpty();
}
function isImpossibleValid(s) {
var isLengthOdd = (s.length % 2 === 1);
var isEmpty = (s.length === 0);
return isLengthOdd || isEmpty;
}
function initBracketStack() {
bracketStack = [];
}
function getNewOpenBracket(c) {
bracketStack.push(c);
}
function isOpenBracket(c) {
return c in openBracketMapping;
}
function isCorrectCloseBracket(c) {
var stackTop = bracketStack.pop();
var expectedChar = openBracketMapping[stackTop];
return expectedChar === c;
}
function isBracketStackEmpty() {
return bracketStack.length === 0;
}
$ node main.js # change to your own filename
You can use console.log("string") to print things out.