-
Notifications
You must be signed in to change notification settings - Fork 0
/
150.逆波兰表达式rpn.js
96 lines (91 loc) · 2.22 KB
/
150.逆波兰表达式rpn.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const isOperator = (s) => ["+", "-", "*", "/"].includes(s);
const parse = (expression) => {
const tokens = [];
for (let i = 0; i < expression.length; i++) {
let token = "";
if (isOperator(expression[i]) && isOperator(tokens[tokens.length - 1])) {
token = expression[i];
i++;
}
while (/\d/.test(expression[i])) {
token = token + expression[i];
i++;
}
if (token) {
tokens.push(Number(token));
i--;
} else {
if (expression[i] !== " ") {
tokens.push(expression[i]);
}
}
}
return tokens;
};
const transform = (tokens) => {
const operators = [];
const result = [];
for (let i = 0; i < tokens.length; i++) {
const ele = tokens[i];
if (typeof ele === "number") {
result.push(ele);
} else {
if (ele === "*" || ele === "/" || ele === "(") {
operators.push(ele);
} else if (operators[operators.length - 1] === "(") {
operators.push(ele);
} else if (ele === ")") {
while (operators[operators.length - 1] !== "(") {
result.push(operators.pop());
}
operators.pop();
} else {
while (operators.length > 0) {
result.push(operators.pop());
}
operators.push(ele);
}
}
}
while (operators.length > 0) {
result.push(operators.pop());
}
return result;
};
const calc = (tokens) => {
let stack = [];
for (let i = 0; i < tokens.length; i++) {
const ele = tokens[i];
if (typeof ele === "number") {
stack.push(ele);
} else {
const right = stack.pop();
const left = stack.pop();
switch (ele) {
case "+":
stack.push(left + right);
break;
case "-":
stack.push(left - right);
break;
case "*":
stack.push(left * right);
break;
case "/":
stack.push(left / right);
break;
}
}
}
return stack[0];
};
const rpn = (expression) => {
const tokens = parse(expression);
const result = transform(tokens);
const value = calc(result);
console.log(value);
return value;
};
rpn("12 + (7 - 3) * 2 + 9 / 3");
rpn("((10 * (6 * ((9 + 3) * 11))) + 17) + 50");
rpn("2 + 30 * (20 - 10) / (100 / 5)");