题目
难度:困难
类型:递归 栈
class Solution {
public:
int calculate(string s) {
//递归 2020.3.29 先把空格搞定
int j = 0;
for(int i = 0; i < s.size(); ){
while(i < s.size() && s[i]==' ') i++;
while(i < s.size() && s[i] != ' ') s[j++] = s[i++];
while(i < s.size() && s[i]==' ') i++;
}
int st = 0;
s.erase(j);
return calc(s, st);
}
int calc(string& s, int &i){
int cnt = 0, t = 0;
bool flag = true;
while(i < s.size()){
if(s[i] =='('){
int u = calc(s, ++i);
if(flag) cnt += u;
else cnt -= u;
}else if(s[i] ==')'){
if(flag) cnt += t;
else cnt -= t;
++i;
return cnt;
}else if(isdigit(s[i])){
t = t*10 -'0'+s[i];
i++;
}else {
if(flag) cnt += t;
else cnt -= t;
t = 0;
if(s[i] =='+') flag = true;
else flag = false;
i++;
}
}
if(flag) cnt += t;
else cnt -= t;
return cnt;
}
};