蓝桥杯 正则问题
问题描述
考虑一种简单的正则表达式:
只由 x ( ) | 组成的正则表达式。
小明想求出这个正则表达式能接受的最长字符串的长度。
例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。
输入格式
一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
输出格式
这个正则表达式能接受的最长字符串的长度。
样例输入
((xx|xxx)x|(x|xx))xx
样例输出
6
数据规模和约定
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入…” 的多余内容。
注意:
main函数需要返回0;
只使用ANSI C/ANSI C++ 标准;
不要调用依赖于编译环境或操作系统的特殊函数。
所有依赖的函数必须明确地在源文件中 #include
不能通过工程设置而省略常用头文件。
提交程序时,注意选择所期望的语言类型和编译器类型
提交地址
解题思路:利用栈将括号去除掉,最后只剩下x和 | ,只要判断 | 两边的字符串哪个长就可以。(原本想直接将数字压栈的,没有想到两个数字(都是个位数字,最终把他们当成一个个位,一个十位加在了一起)在一起相邻的情况,所以直接将同等数量的‘x’压入栈,没想到时间没有超时!!!)。
AC代码
#include <bits/stdc++.h>
using namespace std;
int fun(string ss){
stack<char> st;
int len=ss.size();
int id=0;
while(id<len){
if(ss[id]==')'){ //压栈处理,遇到')'便处理,匹配最近的一个左括号
char k;
k=st.top();
st.pop();
int num=0;
int res=0;
while(k!='('){ //计算在一对匹配括号内的x的最大数量是多少
if(k=='x'){
num++;
}else if(k=='|'){
if(res<num)
res=num;
num=0;
}
k=st.top();
st.pop();
}
if(res<num)
res=num;
while(res--){ //将本次处理括号得到的最大数量的’x‘压入栈
st.push('x');
}
}else{
st.push(ss[id]);
}
id++;
}
int res=0;
int num=0;
while(!st.empty()){ //处理栈里面的数据
char k=st.top();
st.pop();
if(k=='x'){
num++;
}else if(k=='|'){
if(res<num)
res=num;
num=0;
}
}
if(res<num)
res=num;
return res;
}
int main()
{
string s;
cin>>s;
cout<<fun(s);
}
错误代码(压入数字的思路)
#include <bits/stdc++.h>
using namespace std;
int fun(string ss){
stack<char> st;
int len=ss.size();
int id=0;
while(id<len){
if(ss[id]==')'){
char k;
k=st.top();
st.pop();
int count=0;
int num=0;
int res=0;
while(k!='('){ //计算在一对括号内的x的最大数量是多少
if(isdigit(k)){
num+=(k-'0')*(int)pow(10,count);
count++;
}else if(k=='x'){
count=0;
num++;
}else if(k=='|'){
if(res<num)
res=num;
num=0;
count=0;
}
k=st.top();
st.pop();
}
if(res<num)
res=num;
if(res<10){
while(res--){
st.push('x');
}
}else{
while(res){
if(res>10){
st.push(res/10+'0');
res%=10;
}else{
st.push(res+'0');
res=0;
}
}
}
}else{
st.push(ss[id]);
}
id++;
}
int res=0;
int num=0;
int count=0;
while(!st.empty()){ //计算在一对括号内的x的最大数量是多少
char k=st.top();
st.pop();
if(isdigit(k)){
num+=(k-'0')*(int)pow(10,count);
count++;
}else if(k=='x'){
count=0;
num++;
}else if(k=='|'){
if(res<num)
res=num;
num=0;
count=0;
}
}
if(res<num)
res=num;
return res;
}
int main()
{
string s;
cin>>s;
cout<<fun(s);
}