LuckyWinty / fe-weekly-questions

A pro to record some interview questions every week...
MIT License
341 stars 34 forks source link

如何判断左右小括号是否全部匹配。如 ( ( ))()((((())))) #18

Open LuckyWinty opened 4 years ago

LuckyWinty commented 4 years ago
    const judgeBracketsMatch = (s)=> {
        const result = [];
        for(let i = 0;i < s.length;i++){
            if(s[i] === '('){
                result.push(s[i])
            }
            if(s[i] === ')'){
                result.pop()
            }
        }
        if(result.length){
            return false
        }else{
            return true
        }
    }
beMySun commented 4 years ago
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    var stack = []
    var map = { 
        '(' : ')',
        '[': ']',
        '{': '}'
    }

    for (var char of s) {
        if(char in map) {
            stack.push(char)
        } else {
            if( !stack.length || char != map[stack.pop()]) {
                return false
            }
        }
    }

    // 如果最后stack 里没有元素了, 就一定是匹配的
    return !stack.length
};
Luizzzzz commented 4 years ago
const judgeBracketsMatch = s=>{
   let a = [...[...s.replace(/[^\(\)]/g,'')].reduce((m, k) => m.set(k, (m.get(k) || 0) + 1), new Map()).values()];
    return a[0] === a[1]
}
LuckyWinty commented 4 years ago
const judgeBracketsMatch = s=>{
   let a = [...[...s.replace(/[^\(\)]/g,'')].reduce((m, k) => m.set(k, (m.get(k) || 0) + 1), new Map()).values()];
    return a[0] === a[1]
}

简单跑了一下,你的是对的。你的markdown代码格式可以加上哦~比如js 代码

zacard-orc commented 4 years ago
+ const neOps = [')',']','}'];
+ if( neOps.includes(char) && ( !stack.length || char !== map[stack.pop()]))