【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
};
相关推荐
User_芊芊君子3 小时前
影音自由新玩法:Plex+cpolar 解锁异地访问,告别网盘限速烦恼
服务器·nginx·测评
张李浩3 小时前
Leetcode 054螺旋矩阵 采用方向数组解决
算法·leetcode·矩阵
big_rabbit05023 小时前
[算法][力扣101]对称二叉树
数据结构·算法·leetcode
wanhengidc3 小时前
云手机的运行环境如何
运维·服务器·游戏·智能手机·生活
炸膛坦客3 小时前
Linux - Ubuntu - PC端:(三)切换中英文,Fcitx5
linux·ubuntu
7yewh3 小时前
jetson_yolo_deployment 01_linux_dev_env
linux·嵌入式硬件·yolo·机器人·嵌入式
cyber_两只龙宝3 小时前
【Haproxy】Haproxy的算法详解及配置
linux·运维·服务器·云原生·负载均衡·haproxy·调度算法
阿常呓语4 小时前
Linux命令 jq详解
linux·运维·shell·jq
君生我老5 小时前
Linux 权限
linux
hy____1235 小时前
Linux_网络基础3
linux·服务器·网络