【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
};
相关推荐
Amelio_Ming23 分钟前
linux 内核 static-key机制分析
linux
yl--炼气31 分钟前
windows下wsl-ubuntu子系统的位置怎样从C盘转到其他盘
linux·运维·ubuntu
博睿谷IT99_1 小时前
红帽认证 Linux安全 级别
linux·运维·安全
超爱吃香菜的菜鸟1 小时前
关于我的服务器
运维·服务器
Cv打怪升级2 小时前
ubuntu 常用指令
linux·运维·ubuntu
用手码出世界2 小时前
【Linux】进程池bug、命名管道、systemV共享内存
linux·运维·bug
LL1681992 小时前
SSM考研助手管理系统
java·服务器·开发语言·数据库·学习
正点原子3 小时前
【正点原子STM32MP257连载】第二章 ATK-DLMP257B使用前准备 #串口软件 #MobaXterm
linux·stm32·单片机·嵌入式硬件
MobiCetus3 小时前
Linux Kernel 7
linux·运维·服务器·windows·ubuntu·centos·gnu
西洼工作室3 小时前
centos时间不正确解决
linux·运维·centos