-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.cpp
More file actions
76 lines (71 loc) · 1.81 KB
/
program.cpp
File metadata and controls
76 lines (71 loc) · 1.81 KB
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
/**********************************************************
* Time : 36 ms
* https://leetcode.com/submissions/detail/34495065/
**********************************************************/
#include "../include/prevector.h"
#include <stack>
using std::stack;
int calculate(string s)
{
vector<char> operations;
vector<char> rever_marks;
stack<bool> reversions;
bool rever_mark = false;
for (char& ch : s)
{
switch (ch)
{
case '+':
case '-':
operations.push_back(ch);
rever_marks.push_back(rever_mark);
ch = ' ';
break;
case '(':
if (!operations.empty() && operations.rbegin()[0] == '-') rever_mark = !rever_mark;
reversions.push(!operations.empty() && operations.rbegin()[0] == '-');
ch = ' ';
break;
case ')':
if (reversions.top()) rever_mark = !rever_mark;
reversions.pop();
ch = ' ';
break;
}
}
stringstream ss(s);
int rst = 0;
ss >> rst;
cout << endl;
// PrintVector(operations);
// PrintVector(rever_marks);
for (int i = 0; i != operations.size(); i++)
{
int n = 0;
ss >> n;
switch (operations[i]) {
case '+':
rst += rever_marks[i] ? -n : n;
break;
case '-':
rst -= rever_marks[i] ? -n : n;
break;
}
}
return rst;
}
int Mymain()
{
string tests[] = {
"2 ",
"1 + 1",
" 2-1 + 2 ",
"2-(5-6)",
"(3-(2-(5-(9-(4)))))",
"(1+(4+5+2)-3)-(6-8)"
};
for (string& s : tests)
{
cout << s << ":\t" << calculate(s) << endl;
}
}