题目
代码(10.1 首刷看解析)
class Solution {
public:
int calculate(string s) {
stack<int> sk; // 存储正负号
sk.push(1);
int sign = 1;
int res = 0;
int i = 0;
while(i < s.size()) {
if(s[i] == ' ') {
i++;
} else if(s[i] == '+') {
sign = sk.top();
i++;
} else if(s[i] == '-') {
sign = -sk.top();
i++;
} else if(s[i] == '(') {
sk.push(sign);
i++;
} else if(s[i] == ')') {
sk.pop();
i++;
} else {
long long num = 0;
while(i < s.size() && isdigit(s[i])) {
num = num*10+s[i]-'0';
i++;
}
res += num*sign;
}
}
return res;
}
};
代码(10.19 二刷看解析)
递归
class Solution {
public:
int calculate(string s) {
int i = 0;
return dfs(s, i);
}
int dfs(string& s, int& i) {
char sign = '+';
int num = 0;
vector<int> sk;
while(i < s.size()) {
char c = s[i++];
cout<<c<<" ";
if(isdigit(c)) {
num = num*10 + (c-'0');
}
if(c == '(') {
num = dfs(s, i);
}
if((!isdigit(c) && c != ' ') || i == s.size()) {
if(sign == '+') {
sk.push_back(num);
} else if(sign == '-') {
sk.push_back(-num);
}
sign = c;
num = 0;
}
if(c == ')') {
break;
}
}
return accumulate(sk.begin(), sk.end(), 0);
}
};