Home > Blockchain >  Valid Parentheses. Gives a wrong boolean (JS problems on LeetCode)
Valid Parentheses. Gives a wrong boolean (JS problems on LeetCode)

Time:06-01

Trying to solve a problem at LeetCode called "Valid Parentheses".

Conditions are:

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order.

I wrote a function and it's working in this snippet:

let arr = ['()']

var isValid = function (data) {
    let stack = [];
    const bracketsArray = {
      '{':'}',
      '[':']',
      '(':')'
    }
            
    for (i=0; i < data[0].length; i  ) {
        if (data[0][i] == '{' || data[0][i] == '(' || data[0][i] == '[') {
            stack.push(data[0][i]);
        } else if (data[0][i] == '}' || data[0][i] == ']' || data[0][i] == ')') {
            if (bracketsArray[stack[stack.length-1]] == data[0][i]) {
              stack.pop()
            }
        }  
    }
    
    if (stack.length == 0) {
      return true
    } else {
      return false
    }
}

console.log(isValid(arr))

Function gives a correct output (boolean) But when I run this code at LeetCode for some reason the same code gives me a wrong boolean.

Don't understand what is wrong.

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    let stack = [];
    const bracketsArray = {
      '{':'}',
      '[':']',
      '(':')'
    }
    
    
    for (i=0; i < s[0].length; i  ) {
        if (s[0][i] == '{' || s[0][i] == '(' || s[0][i] == '[') {
            stack.push(s[0][i]);
        } else if (s[0][i] == '}' || s[0][i] == ']' || s[0][i] == ')') {
            if (bracketsArray[stack[stack.length-1]] == s[0][i]) {
              stack.pop()
            }
        }  
    }

   if (stack.length == 0) {
     return true;
   } else {
     return false;
   }
};

Any advice?

CodePudding user response:

On LeetCode the function parameter is a string, but in your tests you are passing an array, and also your function code expects an array, since it accesses the string with s[0], instead of s.

Unrelated, but:

  • Your code fails when the input is just a closing bracket. This is because your loop doesn't break with return false when a non-matching closing bracket is encountered. This should happen in the else part of if (bracketsArray[stack[stack.length-1]] == s[i]) {

  • Don't use an undeclared variable i, which will then implicitly become a global variable (if running in non-strict mode).

  • Don't name your variable bracketsArray since it is not an array.

  • Make more use of that object, instead of making three comparisons with opening brackets.

  • The final if...then is overkill for just returning the value of a boolean expression.

So:

var isValid = function(s) {
    const stack = [];
    const brackets = {
      '{':'}',
      '[':']',
      '(':')'
    }
    const closing = Object.values(brackets);
    
    for (let ch of s) {
        if (brackets[ch]) {
            stack.push(brackets[ch]);
        } else if (ch == stack.at(-1)) {
            stack.pop()
        } else if (closing.includes(ch)) {
            return false;
        }
    }

    return !stack.length;
};

console.log(isValid("{([])}")); // true
console.log(isValid("]")); // false

CodePudding user response:

The way you are accessing the current character of the iteration is wrong. Instead of doing s[0][i], simply do s[i].

s[0][i] accesses the first character, and then attempts to get the i-th entry from it (which is undefined).

var isValid = function(s) {
    let stack = [];
    const bracketsArray = {
      '{':'}',
      '[':']',
      '(':')'
    }
    
    
    for (i=0; i < s.length; i  ) {
        if (s[i] == '{' || s[i] == '(' || s[i] == '[') {
            stack.push(s[i]);
        } else if (s[i] == '}' || s[i] == ']' || s[i] == ')') {
            if (bracketsArray[stack[stack.length-1]] == s[i]) {
              stack.pop()
            }
        }  
    }

   if (stack.length == 0) {
     return true;
   } else {
     return false;
   }
};

isValid("{([])}") // true
isValid("{([)}") // false
  • Related