用堆栈处理字符串的题目,一开始没思路想不起来怎么进出栈处理,后来看了题解豁然开朗,输入应该一次输入全了而不是循环输入,否则很不好处理,直接输入到一个string串s中。
然后对这个string串进行处理,申请一个栈空间st,如果是string串的第一个数字,直接入栈,否则就是对符号的判断,加法减法的优先级没有乘除高,直接入栈,后续sum再操作,乘除则是pop出栈顶元素,与符号后一位的元素进行符号位的运算,将运算结果入栈即可,代码如下。
#include <bits/stdc++.h>
using namespace std;
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0),cout.tie(0);
int n;
cin>>n;
while(n--){
string s;
cin>>s;
stack<int> st;
for(int i=0;s[i]!='\0';i++){
if(s[i]>='0'&&s[i]<='9'){
st.push(s[i]-'0');
}
else if(s[i]=='+'){
st.push(s[++i]-'0');
}
else if(s[i]=='-'){
st.push('0'-s[++i]);
}
else if(s[i]=='x'){
int temp=st.top();
st.pop();
st.push(temp*(s[++i]-'0'));
}
else if(s[i]=='/'){
int temp=st.top();
st.pop();
st.push(temp/(s[++i]-'0'));
}
}
int sum=0;
while(!st.empty()){
sum+=st.top();
st.pop();
}
if(sum==24) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}