分析
C++ 代码
#include<bits/stdc++.h>
using namespace std;
//Tools
#define ffor(i,s,e) for(int i=s;i<e;i++)
#define out(x) cout<<x<<" "
#define nl cout<<endl //nextline
//vars
stack<int> stk;
//fun
int play();
int main(){
cout<<play()<<endl;
return 0;
}
bool isNum(int n){
//将栈内的两个符号,|用负二代指和左括号用负一代指
return n>0;
}
int countx(string &str,int s){
int old=s;
while(str[s]=='x') ++s;
return s-old;
}
void PushNum(int n){//数字n待入栈
if(stk.empty()){
stk.push(n);
return ;
}
int c=stk.top();
if(isNum(c)){
stk.pop();
PushNum(n+c);//将直接连的数字一直向下合并
}else{
stk.push(n);
}
}
int getMax(){
int maxV=stk.top();stk.pop();
while(!stk.empty()&&stk.top()==-2){//下一个是|
stk.pop();//弹出|
int n=stk.top();stk.pop();
maxV=max(maxV,n);
}
return maxV;
}
int play(){
string str;
cin>>str;
int n=str.size();
ffor(i,0,n){
char now=str[i];
if(now=='x'){
int nx=countx(str,i);
PushNum(nx);
i+=nx-1;
}else if(now=='('){
stk.push(-1);
}else if(now=='|'){
stk.push(-2);
}else{
int m=getMax();
if(stk.top()==-1) stk.pop();//弹出左括号
PushNum(m);
}
/*查看栈内情况
stack<int> t(stk);
while(!t.empty()){
if(t.top()==-1) out('(');
else if(t.top()==-2) out('|');
else out(t.top());
t.pop();
}
nl;
*/
}
return getMax();
}
// xx(xxx)|(xxxx|x)xxx