20. Valid Parentheses

题目

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.

题解

思路:

题意:输入一个只包含括号的字符串,判断括号是否匹配

模拟堆栈,读到左括号压栈,读到右括号判断栈顶括号是否匹配

var isValid = function (s) {
    var stack = [];
    var i = 0;
    var top;
    while (i < s.length) {
      //左括号压栈
        if ((s[i] === "(") || (s[i] === "[") || (s[i] === "{")) {
            stack.push(s[i]);
        } else {
            //右括号判断是否匹配,匹配则出栈,不匹配则return false;
            top = stack[stack.length - 1];
            if (s[i] === ")" && top !== "(") {
                return false;
            }
            if (s[i] === "]" && top !== "[") {
                return false;
            }
            if (s[i] === "}" && top !== "{") {
                return false;
            }
            stack.pop();
        }
        i = i + 1;
    }
    //判断栈中是否有多余左括号
    if (stack.length > 0) {
        return false;
    }
    return true;
};
原文地址:https://www.cnblogs.com/bubbleStar/p/6120956.html