【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
};
相关推荐
heartbeat..1 小时前
零基础学 SQL:DQL/DML/DDL/DCL 核心知识点汇总(附带连接云服务器数据库教程)
java·服务器·数据库·sql
那些年的笔记1 小时前
Linux屏幕旋转方法
linux·运维·服务器
XiaoHu02071 小时前
Linux网络编程套接字
linux·服务器·网络·git
竹之却2 小时前
CentOS 系列,防火墙相关指令
linux·运维·centos
gaize12132 小时前
科普篇“机架、塔式、刀片”三类服务器对比
运维·服务器
咕噜企业分发小米2 小时前
如何利用云服务器搭建游戏服务器并实现跨平台游戏?
运维·服务器·游戏
一颗青果2 小时前
进程组 | 会话 |终端 | 前台后台 | 守护进程
linux·运维·jvm
古城小栈2 小时前
Rust 交叉编译:Windows ====> Linux (musl 静态编译)
linux·windows·rust
!执行2 小时前
高德地图 JS API 在 Linux 系统的兼容性解决方案
linux·前端·javascript
有一个好名字3 小时前
力扣-确定两个字符串是否接近
算法·leetcode·职场和发展