【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
};
相关推荐
运维行者_4 小时前
Applications Manager中的Redis监控
大数据·服务器·数据库·人工智能·网络协议
xingyuzhisuan7 小时前
网络 Token 常见故障原理,基础排查科普
运维·服务器·网络·php
圣保罗的大教堂7 小时前
leetcode 2540. 最小公共值 简单
leetcode
wljy18 小时前
二、进制状态转换
linux·运维·服务器·c语言·c++
week@eight8 小时前
Linux - Doris
linux·运维·数据库·mysql
平行云9 小时前
实时云渲染预启动技术解析:UE数字孪生应用的延迟优化机制(二)
linux·unity·ue5·webgl·实时云渲染·云桌面·像素流
看到代码头都是大的9 小时前
CentOS环境下手动升级openssl、openssh
linux·运维·centos
浮生若城9 小时前
Linux——Ext系列文件系统
linux·运维·服务器
ITyunwei09879 小时前
主流 SaaS 工单系统对比
运维·服务器·人工智能
枳实-叶9 小时前
【Linux驱动开发】第16天:按键中断完整实战
linux·运维·驱动开发