【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
};
相关推荐
怀旧,几秒前
【Linux系统编程】7. 进程的概念(上)
linux·运维·服务器
7***n7525 分钟前
API网关设计模式
linux·服务器·设计模式
哈里谢顿1 小时前
环境变量 HTTP_PROXY/HTTPS_PROXY 深度解析:为什么 cURL 行,Docker 不行?
linux
馨谙1 小时前
使用 systemd 用户服务管理容器:从概念到实践
linux·容器
人工智能训练2 小时前
Windows中如何将Docker安装在E盘并将Docker的镜像和容器存储在E盘的安装目录下
linux·运维·前端·人工智能·windows·docker·容器
zzzsde2 小时前
【Linux】基础开发工具(1):软件包管理器&&vim编辑器
linux·运维·服务器
tan180°2 小时前
Linux网络TCP(上)(11)
linux·网络·c++·后端·tcp/ip
断水客2 小时前
如何在手机上搭建Linux学习环境
linux·运维·学习
会飞的土拨鼠呀2 小时前
ubuntu24安装snmp服务
linux·运维
胖好白2 小时前
【RK3588开发】模型部署全流程
linux·人工智能