蓝桥杯历届试题——正则问题(用非递归的方法)
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
/*
定义:
xx 相当于 x+x ;
(x)x 相当于 (x)+x ;
x(x) 相当于 x+(x) ;
(x)(x) 相当于 (x)+(x) ;
在此题中, '+' 的优先级高于 '|' .
求逆波兰序列思路 :
1. 得到字符 '(' : if 其前驱是 'x' 或 ')' , 相当于先获得字符 '+' ; '(' 进栈 ;
2. 得到字符 'x' :
case 1 : if 其前驱是 'x' 或 ')' , 相当于先获得字符 '+', 再 '1' 进队 ;
case 2 :else '1' 进队;
3. 相当于得到字符 '+' : 出栈,直到栈顶元素是 '(' 或 '|' 或栈空, 出栈的元素同时入队; '+' 入栈 ;
4. 得到字符 '|' : 出栈, 直到遇到元素是 '(' 或栈空, 出栈的元素同时入队; '|' 入栈 ;
5. 得到字符 ')' : 出栈, 直到栈顶元素为 '(' ; 出栈的元素同时入队 ; 栈顶元素出栈 ;
6. 最后所有元素出栈, 出栈的元素同时入队 .
*/
void getRPN(string str, queue<char> &que);
int calculateRPN(queue<char> &que);
int main()
{
string inputStr;
queue<char> que; //获得的逆波兰序列保存在 que
cin >> inputStr;
getRPN(inputStr, que); //求逆波兰序列
cout << calculateRPN(que) <<endl; //计算
return 0;
}
//求逆波兰序列
void getRPN(string str, queue<char> &que)
{
stack<char> stk;
char temp = '\0'; //记录当前读取元素的前驱, 第0个元素没有前驱, 所以默认为 '\0'
for(int i = 0; i < str.length(); i++)
{
switch(str[i])
{
case '(':
if(temp == 'x' || temp == ')')
{
while(!(stk.empty() == true || stk.top() == '(' || stk.top() == '|'))
{
char c = stk.top();
stk.pop();
que.push(c);
}
stk.push('+');
}
stk.push('(');
break;
case 'x':
if(temp == 'x' || temp == ')')
{
while(!(stk.empty() == true || stk.top() == '(' || stk.top() == '|'))
{
char c = stk.top();
stk.pop();
que.push(c);
}
stk.push('+');
}
que.push('1');
break;
case '|':
while(!(stk.empty() == true || stk.top() == '(' ))
{
char c = stk.top();
stk.pop();
que.push(c);
}
stk.push('|');
break;
case ')':
while(!(stk.empty() == true || stk.top() == '(' ))
{
char c = stk.top();
stk.pop();
que.push(c);
}
if(stk.empty() == false) stk.pop();
break;
}
temp = str[i];
}
while(stk.empty() == false)
{
char c = stk.top();
stk.pop();
if(c == '(') break; // 加这句是因为题目测试数据(最后两组)有误
que.push(c);
}
}
//计算结果
int calculateRPN(queue<char> &que)
{
stack<int> stk;
while(que.empty() == false)
{
char ch = que.front();
if(ch == '1')
{
stk.push(1);
}
else
{
int a, b, c;
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
if(ch == '+')
{
c = a + b;
}
else if(ch == '|')
{
c = a > b? a : b;
}
stk.push(c);
}
que.pop();
}
return stk.top();
}