考虑一种简单的正则表达式:
只由 x ( ) | 组成的正则表达式。
小明想求出这个正则表达式能接受的最长字符串的长度。
例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。
输入
----
一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
输出
----
这个正则表达式能接受的最长字符串的长度。
例如,
输入:
((xx|xxx)x|(x|xx))xx
程序应该输出:
6
资源约定:
峰值内存消耗(含虚拟机) < 256M
只由 x ( ) | 组成的正则表达式。
小明想求出这个正则表达式能接受的最长字符串的长度。
例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。
输入
----
一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
输出
----
这个正则表达式能接受的最长字符串的长度。
例如,
输入:
((xx|xxx)x|(x|xx))xx
程序应该输出:
6
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
首先贴一下我自己写的代码,比较麻烦
#include<iostream>
#include<stack>
using namespace std;
int main() {
int count = 0;
stack<char> regular;
stack<int> first;
char a;
while (scanf("%c",&a)&&a!='\n') {
if (a == '(')
regular.push(a);
else if (a == 'x') {
if (regular.top() == '(') {
count++;
regular.push(count+'0');
}
else {
count = regular.top() - '0';
regular.pop();
count++;
regular.push(count+'0');
}
}
else if (a == '|') {
count = regular.top() - '0';
first.push(count);
regular.pop();
count = 0;
}
else if (a == ')') {
count = regular.top() - '0';
regular.pop();
regular.pop();
regular.push(count>first.top() ? count+'0' : first.top()+'0');
first.pop();
}
}
cout << regular.top() - '0';
return 0;
}
然后看到大神写的,利用了递归,十分简练,放到这里以供学习点击打开链接
#include<bits/stdc++.h>
using namespace std;
int Fun(){
char data;
int x=0,y=0;
while(1){
data=getchar();
if (data=='a') x++;
else if (data=='|') {
y=max(x,y);
x=0;
}
else if (data=='(')
x+=Fun();
else {
y=max(x,y);
return y;
}
}
}
int main(){
int ans=Fun();
cout<<ans<<endl;
}