蓝桥杯17年最长正则结果

2019-03-19  本文已影响0人  Daniel梁

题目:

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

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

输入

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

输出

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

例如,
输入:
        ((xx|xxx)x|(x|xx))xx

程序应该输出:
        6

资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗  < 1000ms


请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。

所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
不要使用package语句。不要使用jdk1.7及以上版本的特性。
主类的名字必须是:Main,否则按无效代码处理。

要点:

一般看到正则匹配或者括号匹配都要用到栈结构,通过(和)决定操作

import java.util.Stack;

public class Solution {

    public static void main(String[] args) {
        
        String string = "((xx|xxx)x|(x|xx))xx";
        
        Stack<Character> stack = new Stack<>();
        
        for (int i = 0; i < string.length(); i++) {
            //找到)开始计算 并往回找到与其对应的(
            if (string.charAt(i) == ')')
            {
                String a = "";

                while (stack.peek() != '(')
                    a += stack.pop();

                int maxLength = getMaxLength(a);
                //拿到(xx|xxx)里面的xxx并push回去继续完成下面的计算
                for (int j = 0; j < maxLength; j++)
                    stack.push('x');

            }

           else stack.push(string.charAt(i));

        }

        String last = "";

        while (!stack.isEmpty()) last+=stack.pop();

        System.out.println(getMaxLength(last));
    }
    //计算xx|xxx的情况
    public static int getMaxLength(String str){
        int Max = -1;
        //注意 | 是属于特殊字符,需要加上\\去告诉系统这个是特殊字符(正则),才可以吧两边x从|分开,^那些也如此!
        String[] result = str.split("\\|");
        
        for (int j = 0; j < result.length; j++)
            Max = Math.max(result[j].toCharArray().length,Max);

        return Max;
    }

}
上一篇 下一篇

猜你喜欢

热点阅读