【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
};
相关推荐
m0_6948455715 分钟前
服务器如何配置防火墙规则开放/关闭端口?
linux·服务器·安全·云计算
阿巴~阿巴~1 小时前
Linux基本命令篇 —— alias命令
linux·服务器·bash
好名字更能让你们记住我2 小时前
Linux多线程(十二)之【生产者消费者模型】
linux·运维·服务器·jvm·windows·centos
门思科技2 小时前
设计可靠 LoRaWAN 设备时需要考虑的关键能力
运维·服务器·网络·嵌入式硬件·物联网
小锋学长生活大爆炸2 小时前
【知识】RPC和gRPC
服务器·网络协议·rpc
学习编程的gas2 小时前
Linux开发工具——gcc/g++
linux·运维·服务器
大大。2 小时前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端
嵌入式成长家2 小时前
ubuntu rules 使用规则
linux·ubuntu·rules 使用规则
_可乐无糖2 小时前
AWS WebRTC: 判断viewer端拉流是否稳定的算法
linux·服务器·webrtc·aws
数据智能老司机2 小时前
Linux内核编程——Linux设备模型
linux·架构·操作系统