【LeetCode】20.Valid Parentheses(有效的括号)

描述

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.

Open brackets must be closed in the correct order.

Every close bracket has a corresponding open bracket of the same type.

例子
text 复制代码
Example 1:

Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true
Example 3:

Input: s = "(]"
Output: false
约束 Constraints:
  • 1 <= s.length <= 104
  • s consists of parentheses only ()[]{}.
JS实现
javascript 复制代码
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    let stack = [];
    const pairs = {'}':'{',']':'[',')':'('}
    for(let c of s){
        if( !pairs[c] ){
        	// 碰到左括号压栈
            stack.push(c) 
        }else if( !stack.length || stack.pop() != pairs[c]){
            // 如果碰到右括号找不到左括号(包含 栈为空 场景)则说明输入S不是有效括号
            return false
        }
    }
    // 根据栈内是否还存在左括号判断 输入S 是否有效的括号
    return !stack.length
};
相关推荐
江畔何人初4 小时前
iptables 和 IPVS 代理模式 Service 的区别
linux·运维·服务器·网络·云原生·kubernetes·代理模式
七度黑光7 小时前
用 openclaw 给故障复盘打分:质量审核自动化实践
运维·服务器·前端·数据库·自动化
xuefeiniao7 小时前
docker.desktop无法启动,导出镜像后
服务器·docker
123过去7 小时前
nfc-list使用教程
linux·网络·测试工具·安全
阿豪学编程7 小时前
LeetCode724.:寻找数组的中心下标
算法·leetcode
禹中一只鱼8 小时前
【力扣热题100学习笔记】 - 哈希
java·学习·leetcode·哈希算法
凌波粒9 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
evo-master9 小时前
网络故障排除方法
linux·服务器·网络
爱学习的小囧10 小时前
VMware Horizon 8 智能卡认证信任库配置攻略:新增 Root CA 导入指南
服务器·esxi·vmware·horizon
Magic--12 小时前
深入解析管道:最基础的进程间通信(IPC)实现
java·服务器·unix