Valid parentheses

Given a only include a ‘(‘,’) ‘, ‘{‘,’} ‘, ‘/’, ‘ ‘the string s, determine whether a string is effective.

  1. The opening parenthesis must be closed with a closing parenthesis of the same type.
  2. The opening brackets must be closed in the correct order.

The problem solving code

When there is a close bracket, there is a corresponding open bracket, so directly use the stack simulation.

var isValid = function(s) {
  const stack = []; // Store the parenthesis sequence
  for (let i = 0; i < s.length; i++) {
    const stackTop = stack[stack.length - 1];
    switch (s[i]) {
      // If the open bracket is pushed, it is ok
      case "(": stack.push(s[i]); break;
      case "{": stack.push(s[i]); break;
      case "[": stack.push(s[i]); break;
      // Check whether the top element of the stack is the opposite of the current type parentheses. If it is, then the stack is topped, indicating that the current two parentheses match successfully.
      case ")": if(stackTop ! = ="(") return false; stack.pop(); break;
      case "}": if(stackTop ! = ="{") return false; stack.pop(); break;
      case "]": if(stackTop ! = ="[") return false; stack.pop(); break; }}return! stack.length;// If there is an element in the stack, the parentheses are not all matched.
};
Copy the code