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

A valid string must meet the following requirements:

An open parenthesis must be closed with a close parenthesis of the same type. The left parentheses must be closed in the correct order. The original force buckle

Example 1:

Input: s = "()" output: trueCopy the code

Example 2:

Input: s = "()[]{}" Output: trueCopy the code

Example 3:

Input: s = "(]" Output: falseCopy the code

Example 4:

Input: s = "([)]" Output: falseCopy the code

Example 5:

Input: s = "{[]}" Output: trueCopy the code

They understand and decide if it’s a closed parenthesis expression

And the idea is,

  • Using the array, simulate the stack, stack.
  • Stack.push (item) is pushed when (, {, and [are encountered
  • If (), {, [and stack.top is the corresponding symbol, if it is out of the stack, if it is not an invalid parenthesis expression
  • If stack.length is greater than 0 at the end of the loop, it is not a valid parenthesis expression
var isValid = function(s) {
    let map = {') ':'('.'} ':'{'.'] ':'['};
    let stack=[];
    for (let i = 0 ; i < s.length; i++) {
        let item=s[i];
        if(item==="("||item==="{"||item==="["){
            stack.push(item)
        }else if(map[item]&&stack[stack.length-1]===map[item]){
            stack.pop()
        }else{
            return false}}return stack.length===0
};
Copy the code