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\n", 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\n");
            continue;
        }
        printf("yes\n");
    }
    return 0;
}

 

posted @ 2015-02-07 19:25  moonbay  阅读(163)  评论(0编辑  收藏  举报