判断括弧匹配


/**
 * 每日一题: 2016-06-12
 * 判断一个包含括号的字符串括号是否匹配
 *
 * @from https://www.codewars.com/kata/54b80308488cb6cd31000161
 * @param  {string} str 待判断的字符串
 * @return {boolean} 是否匹配
 */
function groupCheck (str){
    var reg = /\{\}|\[\]|\(\)/g;
    while (str && str.match(reg)) {
        str = str.replace(reg, '');
    }
    return !str;
}

function groupCheck1 (str){
    var temp = str.replace('{}', '').replace('[]', '').replace('()', '');
    // 如果没有可以替换的就跟上一次的字符串一样了,就结束循环
    while (temp !== str) {
        console.log(temp)
        str = temp;
        temp = str.replace('{}', '').replace('[]', '').replace('()', '');
    }
    // 替换完了说明匹配, 没完就是不匹配
    return !temp;
}

console.log( groupCheck('()') );    // true
console.log( groupCheck('{(})') );  // false
console.log( groupCheck('[]{}') );  // true
console.log( groupCheck('[])') );   // false

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 好好学习,天天向上 题目要求 判断字符串中的括号是否能配对,括号不能有交叉,如({[])}是匹配的,(([])和(...
    小草凡阅读 10,762评论 2 3
  • 我最喜欢读《易经》《黄帝内经》《诗词启蒙》因为易经中告诉了我做人,做事的道理,还让我董得了自强不息,读经典是一种快...
    ZZ李梦涵阅读 906评论 1 1
  • 1、 =SIMPLE FACTORY=打完篮球真累,正好边上有个小摊。“来杯可乐。”“我要芬达。”“一瓶矿泉水...
    big5阅读 2,812评论 0 0
  • 考完会从,已是精疲力尽,什么书也不想看,眼看英语六级考试又要来临,还有半个月的时间,对于我这个英语早已退化到小学的...
    Angela木一静阅读 1,111评论 0 0