0

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.

  • 1
    > https://codereview.stackexchange.com/ – ASDFGerte Sep 13 '21 at 12:08
  • Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. Please first ***>>>[Search for related topics on SO](https://www.google.com/search?q=javascript+match+balanced+OR+balancing+brackets+site%3Astackoverflow.com)<<<*** and if you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. Post [here](https://codereview.stackexchange.com) If you just want to know if YOUR code works, – mplungjan Sep 13 '21 at 12:09

1 Answers1

0

We can simply this by using an array as a stack. We will also need an object to represent a KV map where the key is the closing bracket and the value is the opening bracket.

To put this to code:

const str = "{[()([help[(]])]}";

const validStr = (str) => {
  const brackets = [];
  // Map our brackets
  const pairMap = {
    "]": "[",
    "}": "{",
    ")": "(",
  };

for (let i = 0; i < str.length; i++) {
  if (str[i] === '{' || str[i] === '(' || str[i] === '[') {
    brackets.unshift(str[i]);
    continue;
  }

  // Check that the value is in our map (i.e it is a closing bracket)
  if (pairMap[str[i]] !== undefined) {
      if (brackets[0] === pairMap[str[i]]) { // we have a match!
         // pop the "stack"             
         brackets.shift(); 
      } else {
         return false;
      }
    }
  }
  return brackets.length === 0;
}