【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
};
相关推荐
月清晖19 分钟前
centos更换yum源、安装Docker和换源
linux·docker·centos
【 教主 】41 分钟前
<Linux> 多线程
linux·运维·服务器
技术探索者1 小时前
Shell:如何判断两个字符串相等
linux·shell
athena19992701 小时前
服务器对SEO优化效果的影响
服务器
Slow1 小时前
Linux静态库的制作
linux·c语言
一个梦想过上五休二生活的男人1 小时前
Firewalld防火墙(二)
linux·服务器·数据库
一只猿Hou1 小时前
【logback-spring配置不生效,开发环境和生产环境配置不同输出级别】
linux·spring·logback
橘子味的小橙2 小时前
leetCode-hot100-动态规划专题
java·算法·leetcode·动态规划
__AtYou__2 小时前
Golang | Leetcode Golang题解之第206题反转链表
leetcode·golang·题解
gopher95112 小时前
Linux多进程和多线程(五)进程间通信-消息队列
linux·服务器·c语言·开发语言·进程