【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
};
相关推荐
_星辰大海乀3 分钟前
IP 协议
服务器·网络·tcp/ip·nat·子网掩码·ip协议
云里雾里!43 分钟前
力扣 209. 长度最小的子数组:滑动窗口解法完整解析
数据结构·算法·leetcode
屿行屿行44 分钟前
【Linux】Socket编程(基于实际工程分析)
linux·服务器·网络
runepic1 小时前
Python + PostgreSQL 批量图片分发脚本:分类、去重、断点续拷贝
服务器·数据库·python·postgresql
天才程序YUAN1 小时前
从零开始、保留 Windows 数据、安装Ubuntu 22.04 LTS双系统
linux·windows·ubuntu
Evan芙1 小时前
Rocky Linux 9 网卡改名及静态IP地址配置完整步骤
linux·网络·智能路由器
Zeku1 小时前
20251125 - 韦东山Linux第三篇笔记【上】
linux·笔记·单片机
CoderYanger2 小时前
递归、搜索与回溯-穷举vs暴搜vs深搜vs回溯vs剪枝:12.全排列
java·算法·leetcode·机器学习·深度优先·剪枝·1024程序员节
企鹅侠客2 小时前
Linux性能调优 详解磁盘工作流程及性能指标
linux·运维·服务器·性能调优
icy、泡芙2 小时前
TF卡---热插拔
linux·驱动开发