第八届蓝桥杯JavaA正则问题

 描述:正则问题
 考虑一种简单的正则表达式:
 只由 x ( ) | 组成的正则表达式。
 小明想求出这个正则表达式能接受的最长字符串的长度。
 例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。
 输入
 ----
 一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
 输出
 ----
 这个正则表达式能接受的最长字符串的长度。
 例如,
 输入:
 ((xx|xxx)x|(x|xx))xx
 程序应该输出:
 6
 资源约定:
 峰值内存消耗(含虚拟机) < 256M
 CPU消耗  < 1000ms

代码:

    private static String str;
    private static int index;
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        str = cin.nextLine();
        index = 0;
        int longestStr = getLongestStr();
        System.out.println(longestStr);
    }

    /**
     * 思路:利用栈
     * 遇到 ( ,入栈
     * 遇到x 继续直到遇到不是x为止,记录x的个数,入栈
     * 遇到 | ,开一个新的栈
     * 遇到 ) ,新栈出栈val2,回溯,在前一个栈中不断出栈,如果是数值累加得到val1,直到遇到( ,然后比较val1和val2,将大的那个值入栈
     * 最后字符串读到底了,出栈并将数值累加,最后的结果就是最长字符串的长度
     */

    public static int getLongestStr() {

        Stack<String> stack = new Stack<>();
        String ch;
        int cnt = 0;
        while (index < str.length()) {
            ch = str.charAt(index) + "";
            if (ch.equals("(")) {
                stack.push("(");
                index++;
            } else if (ch.equals("x")) {
                cnt = 0;
                while (index < str.length() && (ch = str.charAt(index++) + "").equals("x")) {
                    cnt++;
                }
                stack.push(cnt + "");
                if (index < str.length())
                    index--;
            } else if (ch.equals("|")) {
                index++;
                int val2 = getLongestStr();

                int val1 = 0;
                while (!stack.isEmpty() && !(ch = stack.pop()).equals("(")) {
                    val1 += Integer.valueOf(ch);
                }
                stack.push(val1 > val2 ? val1 + "" : val2 + "");
                index++;
            } else if (ch.equals(")")) {
                return Integer.valueOf(stack.pop());
            }
        }
        //正则表达式读到底了,弹出栈中所有值累加
        int sum = 0;
        while (!stack.isEmpty()) {
            sum += Integer.valueOf(stack.pop());
        }
        return sum;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值