【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
};
相关推荐
yzx99101314 分钟前
服务器生成图片
运维·服务器
db_murphy1 小时前
Oracle数据块8KB、OS默认认块管理4KB,是否需调整大小为一致?
linux
liulilittle2 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
qq_513970444 小时前
力扣 hot100 Day56
算法·leetcode
mCell4 小时前
从删库到跑路?这50个Linux命令能保你职业生涯
linux·windows·macos
杰克逊的日记4 小时前
GPU运维常见问题处理
linux·运维·gpu
caolib5 小时前
无需云服务器的内网穿透方案 -- cloudflare tunnel
运维·服务器·内网穿透·tunnel·cloudflared
誰能久伴不乏5 小时前
Linux系统调用概述与实现:深入浅出的解析
linux·运维·服务器
程序员学习随笔6 小时前
Linux进程深度解析(2):fork/exec写时拷贝性能优化与exit资源回收机制(进程创建和销毁)
linux·运维·服务器
mmoyula6 小时前
【RK3568 PWM 子系统(SG90)驱动开发详解】
android·linux·驱动开发