主要过程:
1.定义全局变量where,用来标记经过一层递归后问题处理到哪里了
2.递归f(i):s[i......],从i位置开始解析,遇到字符串终止或嵌套条件终止就返回
3.返回值负责f(i)这一段的结果
4.f(i)在返回前更新where,让上级函数通过where知道解析到哪里了,进而继续处理
#include<bits/stdc++.h>
#include<cctype>
#include<windows.h>
using namespace std;
#define maxn 100
string str;
int where=0;
int f(int begin){
//准备两个栈
int stk1[maxn];
char stk2[maxn];
//两个顶指针
int cnt1=0,cnt2=0;
int cur=0;
int ans=0;
//入栈操作
for(int i=begin;i<str.length();i++){
if(str[i]==')'){
if(cur!=0){
stk1[cnt1++]=cur;
}
where=i+1;
break;
}else if(str[i]=='('){
cur=0;
int tmp2=f(i+1);
if(stk2[cnt2-1]=='*'){
int hh=stk1[cnt1-1]*tmp2;
stk1[cnt1-1]=hh;
cnt2--;
}else if(stk2[cnt2-1]=='/'){
int hh=stk1[cnt1-1]/tmp2;
stk1[cnt1-1]=hh;
cnt2--;
}else{
stk1[cnt1++]=tmp2;
}
i=where-1;
}
else if(isdigit(str[i])){
cur=cur*10+str[i]-'0';
}else if(!isdigit(str[i])){
if(cur){
stk1[cnt1++]=cur;
}
if(stk2[cnt2-1]=='*'){
int tmp=stk1[cnt1-1]*stk1[cnt1-2];
cnt1--;
cnt2--;
stk1[cnt1-1]=tmp;
}else if(stk2[cnt2-1]=='/'){
int tmp=stk1[cnt1-1]/stk1[cnt1-2];
cnt1--;
cnt2--;
stk1[cnt1-1]=tmp;
}else{
stk2[cnt2++]=str[i];
}
cur=0;
}
}
//清算过程
ans=stk1[0];
for(int i=0;i<cnt2;i++){
if(stk2[i]=='+'){
ans+=stk1[i+1];
}else{
ans-=stk1[i+1];
}
}
return ans;
}
int main(){
cin>>str;
//压栈操作
cout<<f(0)<<endl;
return 0;
}