代码随想录Day11打卡 栈与队列(2)

53 阅读1分钟

20 有效的括号

var isValid = function (s) {
    const stack = []
    for (let i = 0; i < s.length; i++) {
        const c = s.charAt(i)
        if (c === "(" || c === "[" || c === "{") {
            stack.push(c)
        } else {
            if (stack.length === 0) return false
            const t = stack.pop();
            if (c === ")" && t !== "(") {
                return false
            } else if (c === "]" && t !== "[") {
                return false
            } else if (c === "}" && t !== "{") {
                return false
            }
        }
    }
    return stack.length === 0
};

1047 删除字符串的重复项

var removeDuplicates = function (s) {
    const stack = []
    for (let i = 0; i < s.length; i++) {
        if (stack.length > 0 && stack[stack.length - 1] === s.charAt(i)) {
            stack.pop()
        } else {
            stack.push(s.charAt(i))
        }

    }
    return stack.join("")
};

150 逆波兰表达式

var evalRPN = function(tokens) {
    const stack = []
    res = 0
    for (const token of tokens) {
        if (!isOperator(token)) {
            stack.push(parseInt(token))
        } else {
            const num1 = stack.pop(), num2 = stack.pop()
            if (token === "+") {
                res = num2 + num1
            } else if (token === "-") {
                res = num2 - num1
            } else if (token === "*") {
                res = num2 * num1
            } else if (token === "/") {
                res = num2/num1
                if (res < 0) {
                    res = Math.ceil(res)
                } else {
                    res = Math.floor(res)
                }
            }
            stack.push(res)
        }
    }

    return stack.pop()
};

const isOperator = (token) => {
    if (token === "+" || token === "-" || token === "*" || token === "/") {
        return true
    }
    return false
}