【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
};
相关推荐
做怪小疯子12 分钟前
LeetCode 热题 100——哈希——最长连续序列
算法·leetcode·哈希算法
whb23417412415 分钟前
测试linux删除Oracle文件,使用文件句柄恢复
linux·运维·oracle
遇见火星22 分钟前
LINUX的 jq命令行处理json字段指南
java·linux·json·jq
Dream it possible!32 分钟前
LeetCode 面试经典 150_二叉树_二叉树展开为链表(74_114_C++_中等)
c++·leetcode·链表·面试·二叉树
做怪小疯子37 分钟前
LeetCode 热题 100——双指针——三数之和
算法·leetcode·职场和发展
sin_hielo1 小时前
leetcode 2536
数据结构·算法·leetcode
清静诗意1 小时前
Ubuntu 下 PostgreSQL 安装与配置完整指南
linux·ubuntu·postgresql
flashlight_hi1 小时前
LeetCode 分类刷题:203. 移除链表元素
算法·leetcode·链表
py有趣1 小时前
LeetCode算法学习之数组中的第K个最大元素
学习·算法·leetcode
吗~喽1 小时前
【LeetCode】将 x 减到 0 的最小操作数
算法·leetcode