Skip to content

Commit cc25346

Browse files
committed
Add C++ solution for leetcode 224.
1 parent ab4ad45 commit cc25346

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
#include<stack>
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
int calculate(string s) {
10+
stack<int> nums; // 存储原字符串中的数
11+
stack<char> ops; // 存储原字符串中的符号(含括号和+-)
12+
for (int i = 0; i < s.size(); i++)
13+
{
14+
auto c = s[i];
15+
if (c == ' ') continue; // 过滤空格
16+
if (isdigit(c))
17+
{
18+
int n = 0;
19+
int j = i;
20+
while (j < s.size() && isdigit(s[j]))
21+
n = n*10 + (s[j++] - '0');
22+
i = j-1;
23+
nums.push(n);
24+
}
25+
else if (c == '(') ops.push(c);
26+
else if (c == ')')
27+
{
28+
while (ops.top() != '(')
29+
myEval(nums, ops);
30+
ops.pop();
31+
}
32+
else
33+
{
34+
if (i == 0 || s[i - 1] == '(' || s[i - 1] == '+' || s[i - 1] == '-') // 特殊处理符号和正号
35+
nums.push(0);
36+
while (!ops.empty() && ops.top() != '(') /* 由于此题中运算符只有+或-, 故不需要比较不同运算符的优先级了(括号前面已经处理了) */
37+
myEval(nums, ops);
38+
ops.push(c);
39+
}
40+
}
41+
while (!ops.empty()) myEval(nums, ops);
42+
return nums.top();
43+
}
44+
void myEval(stack<int>& nums, stack<char>& ops)
45+
{
46+
if (ops.empty()) return;
47+
int res;
48+
49+
auto b = nums.top();
50+
nums.pop();
51+
int a = 0;
52+
if (nums.size() > 0)
53+
{
54+
a = nums.top();
55+
nums.pop();
56+
}
57+
auto c = ops.top();
58+
ops.pop();
59+
60+
if (c == '+') res = a + b;
61+
else if (c == '-') res = a - b;
62+
nums.push(res);
63+
}
64+
};
65+
66+
// Test
67+
int main()
68+
{
69+
Solution sol;
70+
// string s = "(1+(4+5+2)-3)+(6+8)"; //"-2+ 1";
71+
string s = "1-(-2)"; //"-2+ 1";
72+
auto res = sol.calculate(s);
73+
cout << res << endl;
74+
75+
return 0;
76+
}

0 commit comments

Comments
 (0)