zoukankan      html  css  js  c++  java
  • Java实现蓝桥杯正则问题

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

    例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。
    输入
    一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
    输出
    这个正则表达式能接受的最长字符串的长度。
    样例输入
    ((xx|xxx)x|(x|xx))xx
    样例输出
    6
    PS:
    本题栈的基础应用 思路很简单 ‘(’ ‘x’ ‘|’ 入栈 碰见‘)’然后出栈
    出栈的时候 把他们连一起 然后用‘|’进行切割 模拟或运算
    留下最长的那个字符串 入栈 最后所有的东西都出栈
    在进行上面的操作 不过本题比较坑 括号有不是成对的 吐槽一下 什么破语法

    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());
        }
    }
    
  • 相关阅读:
    LintCode "Maximum Gap"
    LintCode "Wood Cut"
    LintCode "Expression Evaluation"
    LintCode "Find Peak Element II"
    LintCode "Remove Node in Binary Search Tree"
    LintCode "Delete Digits"
    LintCode "Binary Representation"
    LeetCode "Game of Life"
    LintCode "Coins in a Line"
    LintCode "Word Break"
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13078039.html
Copyright © 2011-2022 走看看