【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
};
相关推荐
openHiTLS密码开源社区1 小时前
【密码学实战】openHiTLS passwd命令行:专业密码哈希生成工具
linux·密码学·哈希算法·ldap·密码策略·随机盐值
筵陌1 小时前
深入理解 Reactor 反应堆模式:高性能网络编程的核心
服务器
WTCLLB1 小时前
netgear r6220 路由器,刷openwrt后,系统备份还原
linux·网络·智能路由器·openwrt
迎風吹頭髮2 小时前
UNIX下C语言编程与实践38-UNIX 信号操作:signal 函数与信号捕获函数的编写
linux·c语言·unix
做运维的阿瑞2 小时前
Linux系统性能监控与故障定位实战:CPU/内存/I/O/网络
linux·运维·网络
驱动探索者3 小时前
车库到双子星:惠普的百年科技传奇
linux
阿沁QWQ3 小时前
MySQL服务器配置与管理
服务器·数据库·mysql
wanhengidc3 小时前
云手机能够做些什么?
运维·服务器·人工智能·智能手机·云计算
2401_865854883 小时前
腾讯云手机适用于哪些人群
服务器
zycoder.4 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试