File tree Expand file tree Collapse file tree 2 files changed +45
-2
lines changed Expand file tree Collapse file tree 2 files changed +45
-2
lines changed Original file line number Diff line number Diff line change 2
2
3
3
[ LeetCode solutions] ( http://maskray.me/blog/2014-06-29-leetcode-solutions ) gives some thoughts on selected problems.
4
4
5
- Solved 201/210 problems.
5
+ Solved 202/211 problems.
6
6
7
7
## Database
8
8
@@ -12,6 +12,7 @@ See [database.md](database.md)
12
12
13
13
| # | Title | Solution |
14
14
| ---| ----- | -------- |
15
+ | 227| [ Basic Calculator II] ( /problems/basic-calculator-ii/ ) | [ basic-calculator-ii.cc] ( basic-calculator-ii.cc ) |
15
16
| 226| [ Invert Binary Tree] ( /problems/invert-binary-tree/ ) | [ invert-binary-tree.cc] ( invert-binary-tree.cc ) |
16
17
| 225| [ Implement Stack using Queues] ( /problems/implement-stack-using-queues/ ) | [ implement-stack-using-queues.cc] ( implement-stack-using-queues.cc ) |
17
18
| 224| [ Basic Calculator] ( /problems/basic-calculator/ ) | [ basic-calculator.cc] ( basic-calculator.cc ) |
@@ -222,4 +223,3 @@ See [database.md](database.md)
222
223
| 3| [ Longest Substring Without Repeating Characters] ( /problems/longest-substring-without-repeating-characters/ ) | [ longest-substring-without-repeating-characters.cc] ( longest-substring-without-repeating-characters.cc ) |
223
224
| 2| [ Add Two Numbers] ( /problems/add-two-numbers/ ) | [ add-two-numbers.cc] ( add-two-numbers.cc ) |
224
225
| 1| [ Two Sum] ( /problems/two-sum/ ) | [ two-sum.cc] ( two-sum.cc ) |
225
-
Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments