首页 > 技术文章 > 蓝桥杯-正则表达式

GarrettWale 2020-03-15 21:14 原文

正则表达式

PREV-35

  • 首先看到题目的要求是求解最长的字符串,一看到最长应该想到一般是使用深度优先搜索和动态规划。
  • 本题中求解的是正则表达式,因为符号只有四种,而且括号可以嵌套,所以我们可以从递归的角度求解最长的长度。
  • 当遇到的字符是左括号时,这个时候应该继续递归以等待右括号的出现,当遇到的字符是|时,我们应该想到这表示或者的含义,这个时候需要求解所有|包含的字符串的长度的最大值;当遇到的字符是右括号时,这个时候再直接返回之前,也要求解右括号之前的最大长度。
/*
输入格式
  一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
输出格式
  这个正则表达式能接受的最长字符串的长度。
样例输入
((xx|xxx)x|(x|xx))xx
样例输出
6
*/
package lanQiao;
import java.io.*;
import java.util.*;
public class 正则问题 {
	private static String regx;
	private static int len=0;
	private static int pos=0;
	public static int dfs() {
		int m=0;
		int temp=0;
		while(pos<len) {
			if(regx.charAt(pos)=='(') {
				pos++;
				temp+=dfs();//等待后面的结果
			}else if(regx.charAt(pos)=='x') {
				pos++;
				temp++;
			}else if(regx.charAt(pos)=='|') {
				pos++;
				m=Math.max(temp, m);
				temp=0;
			}else if(regx.charAt(pos)==')') {
				pos++;
				m=Math.max(m, temp);
				return m;
			}
		}
		return m=Math.max(m,temp);
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner cin=new Scanner(System.in);
		regx=cin.nextLine();
		len=regx.length();
		System.out.println(dfs());
	}

}

推荐阅读