问题描述
考虑一种简单的正则表达式:
只由 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
不能通过工程设置而省略常用头文件。
提交程序时,注意选择所期望的语言类型和编译器类型。
思路
采用DFS
遇到“(”,开始新的搜索;
遇到“)”,结束搜索,并找出括号里的最大值
遇到“|”,记录“(”到它之间的字符长度,用于“)”时比较
参考
https://blog.csdn.net/qq_34243930/article/details/79604366?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
运行过程
((xx|xxx)x|(x|xx))xx
1 jin( 0 0
2 jin( 0 0
3 x 1 0
4 x 2 0
5 | 0 2
6 x 1 2
7 x 2 2
8 x 3 2
9 ) 3 3
9 tui 3 0
10 x 4 0
11 | 0 4
12 jin( 0 4
13 x 1 0
14 | 0 1
15 x 1 1
16 x 2 1
17 ) 2 2
17 tui 2 4
18 ) 2 4
18 tui 4 0
19 x 5 0
20 x 6 0
20 ) 6 6
6
答案
package PREV;
import java.util.Scanner;
public class Main {
static int p=0;//当前搜索到第p位
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String re=sc.nextLine();
//System.out.println(re);
int res=dfs(re);
System.out.println(res);
}
//p-当前搜索到第p位
static int dfs(String re)
{
int ans=0;//"("-"|"一小段的字符串长度
int res=0;//总的最大字符串长度
while(p<re.length()){
if(re.charAt(p)=='(') {
p++;
System.out.println(p+" jin"+"( "+ans+" "+res);
ans=ans+dfs(re);
System.out.println(p+" tui "+ans+" "+res);
}
else if(re.charAt(p)==')') {
p++;
break;
}
else if(re.charAt(p)=='|') {
p++;
res=res>=ans?res:ans;
ans=0;//再向右搜索,是新的小段
System.out.println(p+" | "+ans+" "+res);
}
else {//x
p++;
ans++;
System.out.println(p+" x "+ans+" "+res);
}
}
res=res>=ans?res:ans;
System.out.println(p+" ) "+ans+" "+res);
return res;
}
}
来源:CSDN
作者:SaltedFish00
链接:https://blog.csdn.net/weixin_43176384/article/details/104446693