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;
    }
  • 相关阅读:
    openlayers wfs获取要素
    ArcEngine 直连连接SDE
    arcgis中的 style和serverstyle
    C#开源大全
    C#+ArcEngine 序列化和反序列化AE对象
    C# lazy加载
    Testing 理论测试(三)
    软件开发模型种类(7)
    Testing理论测试题(二)
    Testing 理论测试题(一)
  • 原文地址:https://www.cnblogs.com/moonbay/p/4279213.html
Copyright © 2011-2022 走看看