Ques: Given a string containing these characters: ()[]{} 0-9a-z (hyphen not included)
Task: Verify if the brackets are correctly paired in the string. If yes, print "Valid" else print "Invalid" (without quotes).
Samples: Valid:
{(([{cake}]icing))}
Invalid:
()(blue)(pink[)]{}
([[[]])
{})
(){
{()
Solution:
// input = {}{[(abcd)]}}{ : invalid
// input = {[(abcd)]}{} : valid
// output: print valid / invalid
let input = "()(blue)(pink[)]{} ([[[]]) {}) (){ {()"
let iArray = Array.from(input)
let iStack = []
let map = {
opencurly: 0,
opensquare: 0,
opencircle: 0,
closecurly: 0,
closesquare: 0,
closecircle: 0
}
valid = false
function checkValidity() {
for (let i = iArray.length - 1; i >= 0; i--) {
if((iArray[iArray.length-1].charCodeAt(0)>=48 && iArray[iArray.length-1].charCodeAt(0)<=57)
|| (iArray[iArray.length-1].charCodeAt(0)>=65 && iArray[iArray.length-1].charCodeAt(0)<=90)
|| (iArray[iArray.length-1].charCodeAt(0)>=97 && iArray[iArray.length-1].charCodeAt(0)<=122)
|| (iArray[0].charCodeAt(0)>=48 && iArray[0].charCodeAt(0)<=57)
|| (iArray[0].charCodeAt(0)>=65 && iArray[0].charCodeAt(0)<=90)
|| (iArray[0].charCodeAt(0)>=97 && iArray[0].charCodeAt(0)<=122)){
valid = false
break;
}
else valid = true
let poppedItem = iArray.pop()
if(poppedItem == '{'){
map.opencurly += 1
if(map.closecurly > map.opencurly){
iStack.push(poppedItem)
}
else break
}
if(poppedItem == '}'){
map.closecurly += 1
iStack.push(poppedItem)
}
if(poppedItem == '['){
map.opencurly += 1
if(map.closesquare > map.opensquare){
iStack.push(poppedItem)
}
else break
}
if(poppedItem == '['){
map.closesquare += 1
iStack.push(poppedItem)
}
if(poppedItem == '('){
map.opencurly += 1
if(map.closecircle > map.opencircle){
iStack.push(poppedItem)
}
else break
}
if(poppedItem == ')'){
map.closecircle += 1
iStack.push(poppedItem)
}
}
return map.opencurly==map.closecurly && map.opensquare==map.closesquare && map.opencircle==map.closecircle && valid?"valid":"invalid"
}
console.log(checkValidity())
I wrote this solution in Javascript. I would like to know if the approach is correct or there is a better solution to this. Kindly provide your feedbacks.