【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
};
相关推荐
学困昇10 小时前
Linux基础开发工具(下):调试器gdb/cgdb的使用详解
linux·运维·服务器·开发语言·c++
liulilittle10 小时前
Linux shell 搜索指定后缀名文件,并复制到指定目录。
linux·服务器·数据库
必胜刻10 小时前
Redis哨兵模式(Linux)
linux·数据库·redis
双翌视觉10 小时前
服务器电源外观检测智能化机器视觉解决方案
运维·服务器·人工智能·机器学习
学学学无无止境11 小时前
力扣-从中序与后序遍历序列构造二叉树
leetcode
Channing Lewis11 小时前
.ini文件格式
服务器
阿猿收手吧!11 小时前
【Linux】Ubuntu 24安装webbench
linux·运维·ubuntu
pursuit_csdn12 小时前
力扣周赛 - 479
算法·leetcode·职场和发展
高锰酸钾_12 小时前
单机或内网服务器快速部署软件系统完整教程
运维·服务器
恒创科技HK12 小时前
香港服务器受欢迎的原因有哪些
运维·服务器