JS-入栈出栈思维应用

指定一个字符串仅包含 “ { } [ ] ( )” ,封装一个函数 test 返回 指定成对对应为 true ,否则为 false

示例:test("{}[]")  ==> true

       

        test("{}([])") ==> true

        

        test("({(}[]") ==> false

  function test(str) {
            let a = [];
            let strarr = str.split("")
            for (let i = 0; i < strarr.length; i++) {
                if (strarr[i] === " ") { continue }
                if (strarr[i] == "(" || strarr[i] == "[" || strarr[i] == "{") {
                    a.push(strarr[i])
                }
                else {
                    if (!a.length) { return false }
                    else if ((a[a.length - 1] === "(" && strarr[i] === ")")
                        || (a[a.length - 1] === "[" && strarr[i] === "]")
                        || (a[a.length - 1] === "{" && strarr[i] === "}")) {
                        a.pop(a.length - 1)
                    }
                    else { return false }
                }

            }
            if (a.length) { return false }
            return true
        }

猜你喜欢

转载自blog.csdn.net/gsy445566778899/article/details/126742625