题目描述
考虑一种简单的正则表达式:只由 x ( ) | 组成的正则表达式。
小明想求出这个正则表达式能接受的最长字符串的长度。
例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6
输入格式
输入一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
输出格式
输出这个正则表达式能接受的最长字符串的长度。
输入样例
((xx|xxx)x|(x|xx))xx
输出样例
6
本人补充测试数据 (xxx)x|(xx|(xx|x)x(xx)x)
答案是6
思路
首先,题目保证了数据的合法性,可以省去很多麻烦。本题解选择用c++的栈来解题。
可以用getchar(),循环读入字符到栈s1中。
这个题里面主要有两个要注意的地方:
1. 括号先算;
2. 括号后有x,不能将括号数据输出,因为后面可能还有 '或' 运算符。如(xxx)x|xx
解决办法:
如果碰到右括号,则先算括号里面的数据;然后,存入一个标记到栈s1中,表示括号内数据已被计算,将数字存入栈s2。直到数据读完为止。
取出数据:
循环弹出栈s1的元素,碰到标记则加上标记的数字(弹出栈s2的元素),直到s1为空。
代码环节!
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
stack<char> s1;
stack<int> s2;
//(xxx)x|(xx|(xx|x)x(xx)x)
void popFun();
int main(void)
{
char c;
int sum=0;
while((c=getchar()) && c!='\n'){ //读入数据
if(c!=')')
s1.push(c);
else //先算括号
popFun();
}
int tmp=0;
while(s1.size()){ //取出数据
if(s1.top()=='x')
tmp++;
else if(s1.top()=='t'){
tmp+=s2.top();
s2.pop();
}
else if(s1.top()=='|'){
if(tmp>sum)
sum=tmp;
tmp=0;
}
s1.pop();
}
if(tmp>sum)
sum=tmp;
cout<<sum;
return 0;
}
void popFun(){
int maxn=0;
int tmp=0;
while(s1.top()!='('){
if(s1.top()=='x')
tmp++;
else if(s1.top()=='|'){ //判断是否比maxn更大
if(maxn<tmp)
maxn=tmp;
tmp=0;
}
else if(s1.top()=='t'){ //取出标记的数据
tmp+=s2.top();
s2.pop();
}
s1.pop();
}
if(tmp>maxn) //剩余数据判断
maxn=tmp;
s1.pop();//弹出左括号
s1.push('t');//存入标记
s2.push(maxn);//存入标记数据
}