【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
};
相关推荐
无忧.芙桃10 小时前
Linux系统编程(四):用户与权限管理
linux·运维·服务器
最强小杰11 小时前
某 OpenAI 兼容网关上的 `kimi-k3.1-pro`:Cline、Zed 接入与 SSE 排错示例
java·服务器·网络·ai
戊本菌13 小时前
进程(三)进程优先级:谁先上 CPU
linux·c语言·硬件架构
aningx14 小时前
Arch 系用 greetd 实现开机自动进 Plasma Wayland,注销自动回桌面
linux
张小姐的猫15 小时前
【基于 WebSocket 的多用户网页五子棋】—— 整合封装服务器模块设计实现2️⃣
服务器·websocket·网络协议
江无行者15 小时前
Linux 服务器 top 命令详解
linux
LK_0715 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi15 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
HMS工业网络15 小时前
工业远程访问的五项安全部署原则
运维·服务器·安全
文丑颜不良啊16 小时前
LeetCode3341~3360题目解析
java·leetcode