【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
};
相关推荐
涛ing3 小时前
32. C 语言 安全函数( _s 尾缀)
linux·c语言·c++·vscode·算法·安全·vim
__雨夜星辰__3 小时前
Linux 学习笔记__Day2
linux·服务器·笔记·学习·centos 7
大耳朵土土垚3 小时前
【Linux】日志设计模式与实现
linux·运维·设计模式
学问小小谢3 小时前
第26节课:内容安全策略(CSP)—构建安全网页的防御盾
运维·服务器·前端·网络·学习·安全
yaoxin5211234 小时前
第十二章 I 开头的术语
运维·服务器
ProgramHan4 小时前
1992-2025年中国计算机发展状况:服务器、电脑端与移动端的演进
运维·服务器·电脑
深度Linux8 小时前
Linux网络编程中的零拷贝:提升性能的秘密武器
linux·linux内核·零拷贝技术
Joyner20189 小时前
python-leetcode-从中序与后序遍历序列构造二叉树
算法·leetcode·职场和发展
因兹菜9 小时前
[LeetCode]day9 203.移除链表元素
算法·leetcode·链表
LNsupermali9 小时前
力扣257. 二叉树的所有路径(遍历思想解决)
算法·leetcode·职场和发展