• 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;
    }
  • 相关阅读:
    mysql qps tps
    SQL RIGHT JOIN 关键字
    C#的多态性
    c# 与java之间的简单区别
    多少行转多少列
    SQL语句中&、单引号等特殊符号的处理
    sql 函数的理解
    c# 基础之数组(包含三维数组)
    泛型之Dictionary
    在十六进制字符串与数值类型之间转换
  • 原文地址:https://www.cnblogs.com/moonbay/p/4279213.html
Copyright © 2020-2023  润新知