【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
};
相关推荐
运维行者_13 小时前
OPM 与传统管理工具的区别,在网络修复与自动化运维方面的优势在哪里?
运维·服务器·开发语言·网络·自动化·php·ssl
广州灵眸科技有限公司13 小时前
瑞芯微(EASY EAI)RV1126B 音频输入
linux·开发语言·网络·音视频
文弱书生65613 小时前
2-electronbot主控免驱工程结构
linux·单片机·嵌入式硬件
XFF不秃头13 小时前
力扣刷题笔记-旋转图像
c++·笔记·算法·leetcode
铜豌豆_Y14 小时前
【实用】GDB调试保姆级教程|常用操作|附笔记
linux·c语言·驱动开发·笔记·嵌入式
m0_4856146715 小时前
Linux--Docker网络管理
linux·docker·eureka
TG:@yunlaoda360 云老大15 小时前
华为云国际站代理商NAT的规格有哪些?
服务器·网络·华为云
Guheyunyi15 小时前
视频安全监测系统的三大核心突破
大数据·运维·服务器·人工智能·安全·音视频
石像鬼₧魂石15 小时前
HexStrike AI 理想操作流程清单(完整功能版)
linux·人工智能·windows·学习·ubuntu
Xの哲學15 小时前
Linux UPnP技术深度解析: 从设计哲学到实现细节
linux·服务器·网络·算法·边缘计算