20. 有效的括号
栈的经典题目,遇到左括号入栈,遇到右括号看栈顶是否是匹配的左括号,是就出栈,不是直接返回false,最后看栈是否是空的,防止只剩左括号的情况
function isValid(s: string): boolean {
const stack: string[] = []
for (const x of s) {
if (['(', '{', '['].includes(x)) {
stack.push(x)
} else if (x === ')') {
if (stack.pop() !== '(') {
return false
}
} else if (x === '}') {
if (stack.pop() !== '{') {
return false
}
} else if (x === ']') {
if (stack.pop() !== '[') {
return false
}
}
}
return !stack.length
};
1047. 删除字符串中的所有相邻重复项
循环入栈时,相同消除,否则入栈
function removeDuplicates(s: string): string {
const stack: string[] = []
for (const x of s) {
const r = stack.pop()
if (x !== r) {
stack.push(r)
stack.push(x)
}
}
return stack.join('')
};
150. 逆波兰表达式求值
也是经典题目,遇到符号把栈顶和前一个拿出来运算,结果入栈,遇到数字则直接入栈
function evalRPN(tokens: string[]): number {
const symbols = ['+', '-', '*', '/']
const stack: string[] = []
for (const x of tokens) {
if (symbols.includes(x)) {
const r = Number(stack.pop())
const l = Number(stack.pop())
stack.push(String(calc(l, r, x)))
} else {
stack.push(x)
}
}
return Number(stack[0])
};
function calc(x: number, y: number, op: string) {
switch (op) {
case "+":
return x + y
case "-":
return x - y
case "*":
return x * y
case "/":
return x / y >= 0 ? Math.floor(x / y) : Math.ceil(x / y)
}
}