【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
};
相关推荐
Richard.Wong1 小时前
Windows IIS 服务器部署 Vue3 前端项目详细流程
服务器·前端·windows
Nemo_XP1 小时前
C# gridlookupedit选中内容重复还原操作
服务器·前端·c#
青山木1 小时前
Hot 100 --- 在排序数组中查找元素的第一个和最后一个位置
java·数据结构·算法·leetcode
mifengxing2 小时前
LeetCode 238 除自身以外数组的乘积|无除法O(n)时间+O(1)空间双解法
java·算法·leetcode
wsad05323 小时前
CentOS Stream 10 配置静态 IP 完整指南
linux·tcp/ip·centos
Ai拆代码的曹操3 小时前
K8s 实战:CrashLoopBackOff 状态下 kubectl logs 拿不到日志的三层排查方案
linux·docker·kubernetes
tedcloud1233 小时前
Kimi-K3 部署指南:大模型应用开发环境搭建实践
linux·运维·服务器·开源·音视频
深念Y4 小时前
ZTE_UZ901_NVRAM经验总结
linux·服务器·网络·嵌入式硬件·嵌入式·随身wifi
似水এ᭄往昔4 小时前
【Linux网络编程】--TCP_Socket
linux·网络·tcp/ip
无bug代码搬运工4 小时前
LeetCode 42 接雨水:双指针解法详解
算法·leetcode·职场和发展