【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
};
相关推荐
鸠摩智首席音效师1 小时前
如何在 Linux 中将文件复制到多个目录 ?
linux·运维·服务器
香蕉你个不拿拿^1 小时前
Linux进程地址空间解析
linux·运维·服务器
云小逸2 小时前
【nmap源码分析】Target 类——目标主机信息管理的核心引擎
服务器·windows·nmap
人间打气筒(Ada)2 小时前
Linux学习~日志文件参考
linux·运维·服务器·学习·日志·log·问题修复
xuhe22 小时前
Claude Code配合Astro + GitHub Pages:为 sharelatex-ce 打造现代化的开源项目宣传页
linux·git·docker·github·浏览器·overleaf
charlie1145141912 小时前
RK3568跑Arch Linux全路程指南(以正点原子的RK3568开发板为例子)
linux·嵌入式·rootfs·教程·环境配置·嵌入式linux·工程实践
sprintzer3 小时前
2.06-2.15力扣数学刷题
算法·leetcode·职场和发展
爆米花byh3 小时前
在RockyLinux9环境的Doris单机版安装
linux·数据库·database
滴滴答滴答答4 小时前
LeetCode Hot100 之 17 有效的括号
算法·leetcode·职场和发展
老鼠只爱大米5 小时前
LeetCode经典算法面试题 #20:有效的括号(数组模拟法、递归消除法等五种实现方案详细解析)
算法·leetcode··括号匹配·数组模拟法·递归消除法