Created
August 6, 2017 16:36
-
-
Save sanketmaru/e83ce04100966bf46f6e8919a06c33ba to your computer and use it in GitHub Desktop.
Validate brackets if it contains proper opening and closing brackets .
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
function validateBrackets(inputStr) { | |
var inputArr = inputStr.split(""); | |
var openBrackets = ['(', '{', '[']; | |
var closedBrackets = [')', '}', ']']; | |
var circlePairs = { ')' : '('}; | |
var sqPairs = {']' : '['}; | |
var curlyPairs = {'}' : '{'}; | |
var strStack = []; | |
var isValid = true; | |
for(var i=0;i<inputArr.length;i++) { | |
var inputChar = inputArr[i]; | |
if(openBrackets.indexOf(inputChar) >=0){ | |
strStack.push(inputChar); | |
} else { | |
var circlePairIndex = circlePairs[inputChar]; | |
var sqPairsIndex = sqPairs[inputChar]; | |
var curlyPairsIndex = curlyPairs[inputChar]; | |
var foundIndex = circlePairIndex || sqPairsIndex || curlyPairsIndex; | |
if(!foundIndex) { | |
isValid = false; | |
break; | |
} | |
var openBracketFoundIndex = strStack.indexOf(foundIndex); | |
strStack.pop(); | |
} | |
} | |
console.log('strStack.length', strStack.length); | |
if(strStack.length != 0){ | |
isValid = false; | |
} | |
return isValid; | |
} | |
var isValid = validateBrackets('{(())}'); | |
console.log(isValid); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment