给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
整数除法仅保留整数部分。
使用栈
- 时间复杂度O(n),空间复杂度O(n)
- Runtime: 88 ms, faster than 89.01%
- Memory Usage: 43.2 MB, less than 64.04%
/**
* @param {string} s
* @return {number}
*/
var calculate = function(s) {
s = s.replace(/\s/g, '');
if (!s || !s.length) return 0;
const stack = [];
let cur = 0;
let operation = '+';
const len = s.length;
for (let i = 0; i < len; i++) {
const char = s[i];
if (!isNaN(char)) {
cur = cur * 10 + (s[i] - '0');
}
if (isNaN(char) || i === len - 1) {
switch (operation) {
case '+':
stack.push(cur);
break;
case '-':
stack.push(-cur);
break;
case '*':
stack.push(stack.pop() * cur);
break;
case '/':
stack.push(stack.pop() / cur | 0);
}
operation = char;
cur = 0;
}
}
let res = 0;
while (stack.length) {
res += stack.pop();
}
return res;
};
优化的栈方法
- 时间复杂度O(n),空间复杂度O(1)
- Runtime: 84 ms, faster than 94.71%
- Memory Usage: 41.3 MB, less than 93.89%
/**
* @param {string} s
* @return {number}
*/
var calculate = function(s) {
s = s.replace(/\s/g, '');
if (!s || !s.length) return 0;
let last = 0;
let cur = 0;
let operation = '+';
const len = s.length;
let res = 0;
for (let i = 0; i < len; i++) {
const char = s[i];
if (!isNaN(char)) {
cur = cur * 10 + (s[i] - '0');
}
if (isNaN(char) || i === len - 1) {
switch (operation) {
case '+':
res += last;
last = cur;
break;
case '-':
res += last;
last = (-cur);
break;
case '*':
last = last * cur;
break;
case '/':
last = (last / cur | 0);
}
operation = char;
cur = 0;
}
}
res += last;
return res;
};
另外一种
- 时间复杂度O(n),空间复杂度O(n)
- Runtime: 92 ms, faster than 76.52%
- Memory Usage: 47.3 MB, less than 21.78%
/**
* @param {string} s
* @return {number}
*/
var calculate = function(s) {
s = s.replace(/\s/g, '');
let sign = '+';
let stack = [];
let res = 0;
let len = s.length;
let num = 0;
for (let i = 0; i < len; i++) {
let start = i;
while (/[0-9]/.test(s[i])) {
i++;
}
const num = s.substring(start, i) - '0';
switch(sign) {
case '+':
stack.push(num);
break;
case '-':
stack.push(-num);
break;
case '*':
stack.push(stack.pop() * num);
break;
case '/':
stack.push(parseInt(stack.pop() / num));
break;
}
sign = s[i];
}
while (stack.length) {
res += stack.pop();
}
return res;
};