利用STL 中的Stack 求逻辑表达式的值
今天上午做网易游戏的笔试题目,其中有一道是求合法表达式的逻辑值,在做的过程中,一直以为是要用到后缀表达式来进行求解,并且对逻辑符号和数字没有进行很好的处理,晚上的时候仔细想了一下,发现并不是很难,通过一个字符栈和一个数字栈,利用表达式中的每一个逻辑符号都带有一个括号的特点,首先利用循环不断弹出字符栈中的元素,直到找到第一个不是括号的操作符。然后根据这个操作符选择弹出数字栈中的元素个数,并把逻辑值重新压入数字栈中。
#include<iostream>
#include<vector>
#include<algorithm>
#include<stack>
using namespace std;
int main()
{
int N;
cin >> N;
//这个字符串数组就是用来测试用的,在笔试的时候通过循环读入合法表达式
string s[4] = {"(!0)","(0|(1&0))","(0|(1&(!0)))","(0|(1&(!(0|(1&(0|(1&(0|(1&(0|(1&(0|(1&0)))))))))))))"};
for (int i = 0; i < N; ++i)
{
stack<char> c_temp;
stack<int> n_temp;
char c;
int c_1, c_2;
int ij;
for (int k = 0; k < s[i].size(); ++k)
{
if (s[i][k] == '0' || s[i][k] == '1')
n_temp.push(s[i][k]-'0'); //将字符转换为数字
else
c_temp.push(s[i][k]);
}
while (1)
{
while (!c_temp.empty()) //在字符栈中找到第一个逻辑操作符
{
if (c_temp.top() == ')' || c_temp.top() == '(')
{
c_temp.pop();
}
else
{
break;
}
}
if (c_temp.top() != '!') //根据逻辑操作符的种类进行不同的操作
{
if (n_temp.size() > 1)
{
c_1 = n_temp.top();
n_temp.pop();
c_2 = n_temp.top();
n_temp.pop();
if (c_temp.top() == '&') //进行逻辑与操作
{
ij = c_1 & c_2;
n_temp.push(ij);
}
else //进行逻辑或操作
{
ij = c_1 | c_2;
n_temp.push(ij);
}
c_temp.pop(); //弹出操作符
}
}
else //进行逻辑非操作
{
ij = !(n_temp.top());
n_temp.pop();
n_temp.push(ij);
c_temp.pop(); //弹出操作符
}
if (c_temp.empty()==0 && n_temp.size() == 1)
{
cout << n_temp.top() << endl; //输出最终的逻辑表达式的值
break;
}
}
}
system("pause");
return 0;
}