跳到主要内容

227.基本计算器II

链接:227.基本计算器II
难度:Medium
标签:栈、数学、字符串
简介:给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

题解 1 - typescript

  • 编辑时间:2021-03-11
  • 执行用时:148ms
  • 内存消耗:50.6MB
  • 编程语言:typescript
  • 解法介绍:先乘除后加减。
const numReg = /\-?\d+/;
const opMap: Record<string, (num1: number, num2: number) => number> = {
'+': (num1, num2) => num1 + num2,
'-': (num1, num2) => num1 - num2,
'*': (num1, num2) => num1 * num2,
'/': (num1, num2) => ~~(num1 / num2),
};
function calculate(s: string): number {
s = s.replace(/ /g, '');
const len = s.length;
const stack: string[] = [];
const peek = () => stack[stack.length - 1];
// 去乘除
for (let i = 0; i < len; i++) {
let c = s[i];
if (c === '*' || c === '/' || c === '+') {
stack.push(c);
} else if (c === '-') {
if (stack.length === 0) stack.push('0');
stack.push(c);
} else {
while (i < len - 1 && numReg.test(s[i + 1])) {
c += s[i + 1];
i++;
}
const top = peek();
if (stack.length === 0) {
stack.push(c);
} else if (top === '*' || top === '/') {
const op = stack.pop()!;
const num1 = +stack.pop()!;
const num2 = +c;
stack.push(opMap[op](num1, num2) + '');
} else if (top === '-') {
stack[stack.length - 1] = '+';
stack.push(c.startsWith('-') ? c.substr(1) : '-' + c);
} else {
stack.push(c);
}
}
}
// 去加减
const newStack: string[] = [];
for (const c of stack) {
if (numReg.test(c)) {
if (newStack[newStack.length - 1] === '+') {
const op = newStack.pop()!;
const num1 = +newStack.pop()!;
const num2 = +c;
newStack.push(opMap[op](num1, num2) + '');
} else {
newStack.push(c);
}
} else {
newStack.push(c);
}
}
return +newStack[0];
}