PHP developer PHP developer - 3 months ago 24
Javascript Question

Verify or check encodes bracket of string in JavaScript

How can I check all bracket in JavaScript staring..


verify("---(++++)----") -> 1
verify("") -> 1
verify("before ( middle []) after ") -> 1
verify(") (") -> 0
verify("} {") -> 1 //no, this is not a mistake.
verify("<( >)") -> 0
verify("( [ <> () ] <> )") -> 1
verify(" ( [)") -> 0


I have
verify(str)
this will return 1 or 0.i just want to check this
<>,{},[],()
brackets on string,then any one can do this for me. thanks

Answer

Try this

function verify(str) {
  len = str.length;
  b = [];
  j = 0;
  f = 0;
  for (var i = 0; i < len; i++) {
    if (str[i] == "(" || str[i] == "<" || str[i] == "[") {
      b[j] = str[i];
      j++;
    }
    if (str[i] == ")" || str[i] == "]" || str[i] == ">") {
      k = b.length - 1;
      if (str[i] == ")") {
        if (b[k] == "(") {
          b.pop();
          j--;
        } else {
          f = 1;
        }
      } else if (str[i] == "]") {
        if (b[k] == "[") {
          b.pop();
          j--;
        } else {
          f = 1;
        }
      } else if (str[i] == ">") {
        if (b[k] == "<") {
          b.pop();
          j--;
        } else {
          f = 1;
        }
      } else {
        f = 1;
      }
    }
  }
  if (f == 1) return 0;
  else return 1;
}

console.log(verify("---(++++)----"));
console.log(verify(""));
console.log(verify("before ( middle []) after "));
console.log(verify(") ("));
console.log(verify("} {"));
console.log(verify("<(   >)"));
console.log(verify("(  [  <>  ()  ]  <>  )"));
console.log(verify("   (      [)"));