6. Valid Parentheses

一 问题描述

Valid Parentheses

Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    1. Open brackets must be closed in the correct order.
      Note that an empty string is also considered valid.
Example 1:
input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: trueNote:
翻译:

从一组字符串中判断每一个括号是否是合法的相互包裹。

二 解法

1. 第一解法(个人)

思路:

总体来说,使用栈这种数据结构,配合数组的reduce方法遍历。

代码:

// 使用reduce方法辅助遍历
function isValid(s) {
    let map = {
        '(': ')',
        '{': '}',
        '[': ']'
    };
    let res = s.split('').reduce((acc, item) => {
        if (acc === null)
            return null;
        if("([{".indexOf(item) > -1) {
            acc.push(item);
        } else {
            if (map[acc.pop()] !== item) {
                return null;
            }
        }
        return acc;
    }, []);
    return Array.isArray(res) && res.length === 0;
}
结果:
76 / 76 test cases passed.
Status: Accepted
Runtime: 48 ms
Memory Usage: 34.4 MB

2. 第二解法(个人)

思路:

reduce方法固定会遍历所有元素,并且reduce加和的作用不是很需要。可以在匹配到第一个不合法包裹的情况就退出,Array.prototype.some()方法完美符合需求。

代码:

function isValidBetter(s) {
    let map = {
        '(': ')',
        '{': '}',
        '[': ']'
    };
    let acc = [];
    return !s.split('').some((item) => {
        if("([{".indexOf(item) > -1) {
            acc.push(item);  
            return false;
        } else {
            if (map[acc.pop()] !== item) {
                return true;
            }
            return false;
        }
    }) ? acc.length === 0 : false;
}
结果:
76 / 76 test cases passed.
Status: Accepted
Runtime: 48 ms
Memory Usage: 34.5 MB

By DoubleJan
2019.8.22

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值