Skip to content

Commit 5f6b890

Browse files
committed
basic-calculator-ii
1 parent 1938bec commit 5f6b890

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
[LeetCode solutions](http://maskray.me/blog/2014-06-29-leetcode-solutions) gives some thoughts on selected problems.
44

5-
Solved 201/210 problems.
5+
Solved 202/211 problems.
66

77
## Database
88

@@ -12,6 +12,7 @@ See [database.md](database.md)
1212

1313
| # | Title | Solution |
1414
|---| ----- | -------- |
15+
|227|[Basic Calculator II](/problems/basic-calculator-ii/)|[basic-calculator-ii.cc](basic-calculator-ii.cc)|
1516
|226|[Invert Binary Tree](/problems/invert-binary-tree/)|[invert-binary-tree.cc](invert-binary-tree.cc)|
1617
|225|[Implement Stack using Queues](/problems/implement-stack-using-queues/)|[implement-stack-using-queues.cc](implement-stack-using-queues.cc)|
1718
|224|[Basic Calculator](/problems/basic-calculator/)|[basic-calculator.cc](basic-calculator.cc)|
@@ -222,4 +223,3 @@ See [database.md](database.md)
222223
|3|[Longest Substring Without Repeating Characters](/problems/longest-substring-without-repeating-characters/)|[longest-substring-without-repeating-characters.cc](longest-substring-without-repeating-characters.cc)|
223224
|2|[Add Two Numbers](/problems/add-two-numbers/)|[add-two-numbers.cc](add-two-numbers.cc)|
224225
|1|[Two Sum](/problems/two-sum/)|[two-sum.cc](two-sum.cc)|
225-

basic-calculator-ii.cc

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Basic Calculator II
2+
// operator-precedence parser
3+
class Solution
4+
{
5+
public:
6+
int calculate(string s) {
7+
stack<int> xs;
8+
stack<char> ops;
9+
map<char, int> isp, icp;
10+
isp['\0'] = 0; isp['+'] = 3; isp['-'] = 3; isp['*'] = 5; isp['/'] = 5; isp['('] = 1;
11+
icp['\0'] = 0; icp['+'] = 2; icp['-'] = 2; icp['*'] = 4; icp['/'] = 4; icp['('] = 6; icp[')'] = 1;
12+
ops.push('\0');
13+
for (size_t i = 0; i <= s.size(); ) {
14+
char op = i == s.size() ? '\0' : s[i];
15+
if (op == ' ')
16+
i++;
17+
else if (isdigit(op)) {
18+
int x = 0;
19+
do x = x*10+s[i]-'0';
20+
while (isdigit(s[++i]));
21+
xs.push(x); // shift
22+
} else {
23+
i++;
24+
int x, y;
25+
for (; isp[ops.top()] > icp[op]; ops.pop()) {
26+
y = xs.top(); xs.pop();
27+
x = xs.top(); xs.pop();
28+
switch (ops.top()) {
29+
case '+': xs.push(x+y); break;
30+
case '-': xs.push(x-y); break;
31+
case '*': xs.push(x*y); break;
32+
case '/': xs.push(x/y); break;
33+
}
34+
}
35+
if (isp[ops.top()] == icp[op]) // reduce, '(' X ')' => X or '\0' X '\0' => X
36+
ops.pop();
37+
else
38+
ops.push(op); // shift
39+
}
40+
}
41+
return xs.top();
42+
}
43+
};

0 commit comments

Comments
 (0)