【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
};
相关推荐
Adios79413 小时前
设置交集大小至少为2
数据结构·算法·leetcode
海阔天空任鸟飞~13 小时前
Linux 权限 777
linux·运维·服务器
Kina_C16 小时前
Linux iptables 防火墙原理与实操——从四表五链到 NAT 配置
linux·运维·服务器·iptables
wdfk_prog16 小时前
嵌入式面试真题第 15 题:不可恢复异常后的通用崩溃快照、调用栈保存与离线分析架构
linux·开发语言·面试·架构
灵机一物21 小时前
企业选型参考:2026 CXL 内存扩展方案六强测评与落地指南
服务器·网络·数据库·人工智能
Web极客码21 小时前
如何用三段式确定性剪枝,为 LLM Agent 砍掉 35% 的 Token 成本?
服务器·人工智能·算法·机器学习
程序猿乐锅21 小时前
【数据结构与算法 | 第六篇】力扣1109,1094差分数组
java·算法·leetcode
雷工笔记21 小时前
什么是Ubuntu?
linux·运维·ubuntu
yeflx21 小时前
速腾Airy雷达使用记录
java·服务器·网络
公众号:fuwuqiBMC21 小时前
(转自“服务器BMC”)服务器BMC芯片——多Die(芯片)封装
运维·服务器·人工智能