写这篇文章,主要是供自己日后复习用的
历届试题 正则问题
问题描述
考虑一种简单的正则表达式:
只由 x ( ) | 组成的正则表达式。
小明想求出这个正则表达式能接受的最长字符串的长度。
例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是 6。
输入格式
一个由 x()| 组成的正则表达式。输入长度不超过 100,保证合法。
输出格式
这个正则表达式能接受的最长字符串的长度。
样例输入
((xx|xxx)x|(x|xx))xx
样例输出
6
————————————————
解题思路:
import java.util.Scanner;
// 1:无需package
// 2: 类名必须Main, 不可修改
import java.util.*;
public class Main {
static Queue<Character> queue = new LinkedList<>();
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
if(str == null){
System.out.println(0);
}
else{
for(int i = 0;i < str.length();i++){
queue.add(str.charAt(i));
}
int ans = dfs(queue);
System.out.println(ans);
}
scan.close();
}
static int dfs(Queue<Character> string){
int strnum = 0;//记录遇到|之前的字符串长度
int countnum = 0;
while(!string.isEmpty()){
char c = string.poll();
if(c == ')'){
return Math.max(strnum,countnum);
}
if(c == 'x'){
countnum++;
}
else if(c == '|'){//把统计的字符长度赋值给strnum,再统计|后面的,最后比较两个,取最大
strnum = Math.max(strnum,countnum);
countnum = 0;
}
else if(c == '('){
countnum += dfs(string);
}
}
return Math.max(strnum,countnum);
}
}