leetcode 224 - Basic Calculator

https://leetcode.com/problems/basic-calculator/

Convert Infix Expression to Post-Fix Expression: https://condor.depaul.edu/ichu/csc415/notes/notes9/Infix.htm

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
class Solution {
public:
int calculate(string s) {
vector<string> postfix = infix_to_postfix(s);
stack<int> stk;
int result;

for (auto e : postfix) {
if (e == "+" || e == "-") {
int op1 = stk.top(); stk.pop();
int op2 = stk.top(); stk.pop();

if (e == "+")
result = op2 + op1;
else
result = op2 - op1;
stk.push(result);
} else
stk.push(stoi(e));
}

return stk.top();
}

vector<string> infix_to_postfix(string &s) {
vector<string> postfix;
stack<char> stk;
char e;
bool last_is_digit = false;

for (char c : s) {
switch (c) {
case '(':
stk.push(c);
last_is_digit = false;
break;
case ')':
case '+':
case '-':
while (!stk.empty()) {
e = stk.top();
if (e == '(')
break;
postfix.push_back(string(1,e));
stk.pop();
}
if (c == ')')
stk.pop();
else
stk.push(c);
last_is_digit = false;
break;
case ' ':
last_is_digit = false;
break;
default:
if (last_is_digit)
postfix.back().push_back(c);
else
postfix.push_back(string(1,c));
last_is_digit = true;
break;
}
}

while (!stk.empty()) {
e = stk.top(); stk.pop();
if (e == '(') break;
postfix.push_back(string(1, e));
}

return postfix;
}
};