【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
};
相关推荐
那年窗外下的雪.16 分钟前
AIDC 学习日志 Day 3:OSPF Underlay 实验、故障排查与深入解析
服务器·网络·php
hanlin0333 分钟前
刷题笔记:力扣第189题-轮转数组
笔记·算法·leetcode
琥珀色糖35 分钟前
leetcode hot100题(持续更新)移动零(双指针)
算法·leetcode·职场和发展·双指针·移动零
深圳恒讯40 分钟前
CN2 GIA和CN2 GT的区别
运维·服务器·网络
橙-极纪元1 小时前
把docker的镜像文件从一台服务器中,迁移至另一台服务器
服务器·docker·容器
奔跑的架构师1 小时前
[A-49]ARMv9/v8-PSCI接口规范与工作流程简介
android·linux·arm开发·arm
ydyd202604211 小时前
设备OEE怎么提升?数据采集+分析优化的完整方案
java·服务器·前端
hanlin031 小时前
动态规划专练:力扣第718、1143题
算法·leetcode·动态规划
(╹◡╹)2 小时前
11.RK3588本地大模型内存评估优化
java·linux·前端