Javascript Solution


  • 0
    P
    const complements = {
      '(': ')',
      '{': '}',
      '[': ']'
    };
    
    var isValid = function(s) {
      
      // if string length is odd, it is invalid
      if( s.length % 2 !== 0 ) return false;
    
      var stack = [];
    
      for(var i = 0; i < s.length; i ++) {
    
        // if current character is '(,{,[',
        // store the complement in stack
        if (complements[s[i]]) {
          stack.push(complements[s[i]]);
        }
        else {
          if (stack.pop() !== s[i]) return false;
        }
      }
    
      // if there is still any element in stack, the string is invalid.
      if (stack.length > 0) return false;
    
      // everything is fine, string is valid.
      return true;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.