蓝桥杯 正则问题(dfs)

1607: 正则问题

时间限制: 1 Sec  内存限制: 256 MB
提交: 34  解决: 13
[提交][状态][讨论版]

题目描述

考虑一种简单的正则表达式:
只由 x ( ) | 组成的正则表达式。
小明想求出这个正则表达式能接受的最长字符串的长度。  

例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。

输入

一个由x()|组成的正则表达式。输入长度不超过100,保证合法。

输出

这个正则表达式能接受的最长字符串的长度。  

样例输入

((xx|xxx)x|(x|xx))xx

样例输出

6


import java.util.Scanner;

public class Main {
    
    static Scanner sc = new Scanner(System.in);
    static String s;
    static int len,i;
    static int dfs() {
        int max=0,c=0;
        while(i<len) {
            if(s.charAt(i)=='(') {
                i++;
                c+=dfs();
            }
            else if(s.charAt(i)=='|') {
                i++;
                if(max<c) max=c;
                c=0;
            }
            else if(s.charAt(i)==')') {
                i++;
                break;
            }
            else {
                i++;
                c++;
            }
        }
        if(max<c) max=c;
        return max;
    }
    public static void main(String[] args) {
        
        s=sc.next();
        len=s.length();
        System.out.println(dfs());
    }
}

 

posted @ 2018-03-28 21:14  yzm10  阅读(903)  评论(0编辑  收藏  举报