Skip to content

第二十题 - 有效的括号 #21

Description

@laizimo

题目描述

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:
输入: "()"
输出: true

示例 2:
输入: "()[]{}"
输出: true

示例 3:
输入: "(]"
输出: false

示例 4:
输入: "([)]"
输出: false

示例 5:
输入: "{[]}"
输出: true

算法

栈使用

答案

/**
 * 使用栈
 */
var isValid = function(s) {
    // #1 设置栈 和 map
    const stack = [];
    const map = { '[' : ']', '{' : '}', '(' : ')' };
    // #2 遍历字符串
    for (let i = 0; i < s.length; i++) {
        // #3 取出当前字符
        let chat = s[i];
        // #4 判断栈是否为空
        if (!stack.length) {
            // #5 栈为空时,判断是否为左边符号,不是,则返回false
            if (map[chat]) stack.push(chat);
            else return false;
        } else {
            // #6 取出栈顶元素
            let left = stack[stack.length - 1];
            // #7 比较 栈顶元素 和 字符 是否相等,相等,栈推出一位;否则判断是否为左边元素;否则返回false
            if (map[left] === chat) {
                stack.pop();
            } else if (map[chat]) {
                stack.push(chat);
            } else {
                return false;
            }
        }
    }
    // #8 判断栈是否为空
    return !stack.length;
};

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions