algorithm icon indicating copy to clipboard operation
algorithm copied to clipboard

有效的括号

Open JesseZhao1990 opened this issue 7 years ago • 1 comments

image

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    var arr = [];
    s = s.split('');
    for(var i=0;i<s.length;i++){
        if(s[i] == "(" || s[i] == "[" || s[i] == "{"){
            arr.push(s[i])
        }
        
        if(s[i] == ")"){
            if(arr[arr.length-1] == "("){
                arr.pop();
            }else{
                return false
            }
        }
        if(s[i] == "]"){
            if(arr[arr.length-1] == "["){
                arr.pop();
            }else{
                return false
            }
        }
        if(s[i] == "}"){
            if(arr[arr.length-1] == "{"){
                arr.pop();
            }else{
                return false
            }
        }
    }
    if(arr.length>0){
        return false;
    }
    return true;
    
};

LeetCode原题链接:https://leetcode-cn.com/problems/valid-parentheses/description/

JesseZhao1990 avatar Jun 26 '18 09:06 JesseZhao1990

实际编码中,针对标签的匹配必须使用入栈判断,非常实用的数据结构用法

royalrover avatar Aug 07 '18 03:08 royalrover