ForeveHG / Frontend-Daily-Interview

学习,尝试回答一些前端面试题
1 stars 0 forks source link

94. 判断字符串是否按规则闭合 #95

Open ForeveHG opened 3 years ago

ForeveHG commented 3 years ago

这是去年天猫笔试的一道题,具体题目没记录了,大概是这个意思,凑合着看: 规定 [],(),{}是一对,实现一个方法,判断[],(),{}是否成对出现,成对返回true,否则返回false 例如: [abc] //true ([abc)] //false {[]} //true {[] //false

ForeveHG commented 3 years ago
function isCloseTag(str) {
    let openTag = ['[', '(', '{'];
    let closeTag = [']', ')', '}'];
    let tagStack = [];
    let flag = true
    while(str && flag) {
        let chart = str.substr(0, 1);
        str = str.substr(1);
        if(openTag.indexOf(chart) > -1) {
            tagStack.push(chart)
        }
        if(closeTag.indexOf(chart) > -1) {
            let start = tagStack.pop()
            let startTagIdx = openTag.indexOf(start);
            let closeTagIdx = closeTag.indexOf(chart);
            if(startTagIdx !== closeTagIdx) {
                flag = false;
            }
        }
    }
    if(tagStack.length !== 0) flag = false 
    return flag;
}