[LeetCode]20_Valid Parentheses

来源:互联网 发布:淘宝闲鱼官方下载 编辑:程序博客网 时间:2024/05/21 17:15

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

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

括号匹配问题,直接遍历整个字符串,如果遇到左括号则将左括号放入一个栈中,如果遇到右括号则从栈顶取出一个左括号,比对是否是一对,如果不是一对则说明不是标准的括号组形式,最后如果遍历结束栈为空则说明是标准括号组返回true

let isValid = (str)=>{    let left_stack = []    for(let i=0;i<str.length;i++){        if(str[i]==='('||str[i]==='['||str[i]==='{'){            left_stack.push(str[i])        }        if(str[i]===')'){            let left_ = left_stack.pop();            if(left_!=='('){                return false            }        }        if(str[i]===']'){            let left_ = left_stack.pop();            if(left_ !== '['){                return false            }        }        if(str[i]==='}'){            let left_ = left_stack.pop();            if(left_!=='{'){                return false            }        }    }    if(left_stack.length === 0){        return true    }else{        return false    }  }console.log(isValid('['))console.log(isValid('()[]{}'))console.log(isValid('(]'))console.log(isValid("([)]"))console.log(isValid('(('))console.log(isValid('){'))console.log(isValid('([])'))
原创粉丝点击