【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
};
相关推荐
梁正雄32 分钟前
6、prometheus资源规划
运维·服务器·服务发现·prometheus·监控
晨曦之旅44 分钟前
零成本体验云计算!阿贝云免费服务器深度测评
运维·服务器·云计算
工具人55551 小时前
Linux 抓取 RAM Dump 完整指南
linux·运维·安全
不懂音乐的欣赏者1 小时前
Windows 下 ROS/ROS2 开发环境最优解:WSL 比直接安装、虚拟机、双系统更优雅!
linux·windows·ubuntu·ros·wsl·ros2·双系统
谈笑也风生2 小时前
只出现一次的数字 II(一)
数据结构·算法·leetcode
aloha_7892 小时前
测试开发工程师面经准备(sxf)
java·python·leetcode·压力测试
神仙别闹2 小时前
基于C语言 HTTP 服务器客户端的实验
服务器·c语言·http
小狗爱吃黄桃罐头3 小时前
正点原子【第四期】Linux之驱动开发学习笔记-10.1 Linux 内核定时器实验
linux·驱动开发·学习
初听于你3 小时前
运维高级故障排除与恢复-SysRq
运维·服务器·安全
im_AMBER3 小时前
Leetcode 47
数据结构·c++·笔记·学习·算法·leetcode