Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

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

Open
laizimo opened this issue May 31, 2020 · 0 comments
Open

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

laizimo opened this issue May 31, 2020 · 0 comments

Comments

@laizimo
Copy link
Owner

laizimo commented May 31, 2020

题目描述

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

有效字符串需满足:

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

示例 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;
};
# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

1 participant