zoukankan      html  css  js  c++  java
  • bjfu1284 判别正则表达式

    做解析器做得多的我,一上来就觉得要写解析器,麻烦,于是想偷懒用java的正则表达式类Pattern直接进行判断,结果wa了,原因是这题要求的正则表达式只是真正正则表达式的一个子集。比如|12是合法正则表达式,但是此题中属于不合法。还是把代码贴上吧:

    import java.util.Scanner;
    import java.util.regex.Pattern;
    public class Main {
        public static void main(String[] args) {
            Scanner cin = new Scanner(System.in);
            boolean res;
            while(cin.hasNextLine()) {
                String line = cin.nextLine();
                res = true;
                try {
                    Pattern.compile(line);
                }catch(Exception e) {
                    res = false;
                }
                System.out.printf("%s
    ", res ? "yes" : "no");            
            }
        }
    }

    然后就乖乖用c++写递归下降了,写着写着发现挺简单,就一个函数自递归就好了,so easy~~

    /*
     * Author    : ben
     */
    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <cmath>
    #include <ctime>
    #include <iostream>
    #include <algorithm>
    #include <queue>
    #include <set>
    #include <map>
    #include <stack>
    #include <string>
    #include <vector>
    #include <deque>
    #include <list>
    #include <functional>
    #include <numeric>
    #include <cctype>
    using namespace std;
    int get_str(char *str) {
        char c;
        while ((c = getchar()) <= ' ') {
            if(c == EOF) {
                return -1;
            }
        }
        int I = 0;
        while (c > ' ') {
            str[I++] = c; c = getchar();
        }
        str[I] = 0;
        return I;
    }
    int len, c;
    char str[200];
    
    void regex() {
        if (c >= len || (str[c] != '0' && str[c] != '1' && str[c] != '(')) {
            throw 0;
        }
        if (str[c] == '(') {
            c++;
            do {
                regex();
            } while (str[c] != ')');
            c++;
        } else {
            while (str[c] == '0' || str[c] == '1') {
                c++;
            }
        }
        while (str[c] == '*') {
            c++;
        }
        if (str[c] == '|') {
            c++;
            regex();
        }
    }
    
    int main() {
        while ((len = get_str(str)) > 0) {
            c = 0;
            try {
                while (c < len) {
                    regex();
                }
            } catch(int) {
                printf("no
    ");
                continue;
            }
            printf("yes
    ");
        }
        return 0;
    }
  • 相关阅读:
    微信定制开发怎么做?
    bzoj4069【APIO2015】巴厘岛的雕塑
    bzoj3174【TJOI2013】解救小矮人
    bzoj3531【SDOI2014】旅行
    单例模式
    JDK自带的定时任务
    centos6下手工编译vitess
    Rocchio算法
    Excel如何查找名字重复的数据
    MyEclipse8.5快速搭建SSH框架
  • 原文地址:https://www.cnblogs.com/moonbay/p/4279213.html
Copyright © 2011-2022 走看看