【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
};
相关推荐
Evan芙13 分钟前
Bash 变量命名规则与类型使用
linux·运维·开发语言·chrome·bash
Espresso Macchiato14 分钟前
Leetcode 3748. Count Stable Subarrays
算法·leetcode·职场和发展·leetcode hard·leetcode 3748·leetcode周赛476·区间求和
濊繵32 分钟前
Linux网络--Socket 编程 TCP
linux·网络·tcp/ip
menge23331 小时前
Linux网站搭建
linux·运维·网络
Bruce_Liuxiaowei1 小时前
Kali Linux 加入 Windows 域实战指南:解决域发现与加入失败问题
linux·运维·windows
LumenL1u1 小时前
CentOS 7/8/9 上安装 MySQL 8.0+ 完整指南
linux·mysql
梁正雄1 小时前
linux服务-nginx原理与安装-1
linux·运维·nginx
伊卡洛斯az2 小时前
Linux veth
linux·服务器
brucelee1862 小时前
在 Linux Ubuntu 24.04 安装 IntelliJ IDEA
linux·ubuntu·intellij-idea
阿伟实验室2 小时前
debian10部署简易web服务器
运维·服务器·前端