Function for checking the performance of a mathematical expression

The function to check the mathematical expression does not work.

I debugged this on chrome and I saw that when it gets to the first pop ( stack.pop()!== chars[i]), it returns false, but it should not.

var smarter_validate = function(str) {
  var chars = str.split('');
  var stack = [];
  var lookup = {
    '(': ')',
    '[': ']',
    '{': '}',
    '<': '>'
  };
  var left = Object.keys(lookup);
  var right = Object.keys(lookup).map(function(key) {
    return lookup[key]
  });

  for (var i = 0; i < chars.length; i++) {
    if (left.indexOf(chars[i]) !== (-1)) {
      stack.push(chars[i]);
    } else if (right.indexOf(chars[i]) !== (-1)) {
      if ((stack.length === 0) || (stack.pop() !== chars[i])) {
        return false;
      }
    }
  }
  return (stack.length === 0);
};

console.log("SMART VALIDATE" + smarter_validate('(3+4[*2{6+8}])'));
+4
source share
1 answer

In fact, you need to compare the value corresponding to the closing character with chars[i], and not the pop-up value itself.

So you need to do

if (stack.length === 0 || lookup[stack.pop()] !== chars[i]) {

Now that you are {off the stack, you will look for the appropriate closing character from lookupand compare it with the current closing character.


, ,

stack.push(lookup[chars[i]]);
+5

Source: https://habr.com/ru/post/1624001/


All Articles