下面是Java代码实现:

import java.util.Scanner;

public class RecursiveDescentParser { private static int index; // 当前读入单词在字符串中的下标 private static String input; // 待分析的字符串

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    input = sc.nextLine(); // 读入待分析的字符串
    index = 0; // 初始化下标为0
    if (A()) {
        if (index == input.length()) {
            System.out.println("Success");
        } else {
            System.out.println("Error");
        }
    } else {
        System.out.println("Error");
    }
}

// A -> iB*e
private static boolean A() {
    if (input.charAt(index) == 'i') {
        index++;
        if (B()) {
            if (input.charAt(index) == '*') {
                index++;
                if (input.charAt(index) == 'e') {
                    index++;
                    return true;
                }
            }
        }
    }
    return false;
}

// B -> SB | ε
private static boolean B() {
    if (S()) {
        if (B()) {
            return true;
        }
    }
    return true; // ε产生式
}

// S -> [eC] | .i
private static boolean S() {
    if (input.charAt(index) == '[') {
        index++;
        if (input.charAt(index) == 'e') {
            index++;
            if (C()) {
                if (input.charAt(index) == ']') {
                    index++;
                    return true;
                }
            }
        }
    } else if (input.charAt(index) == '.') {
        index++;
        if (input.charAt(index) == 'i') {
            index++;
            return true;
        }
    }
    return false;
}

// C -> eC | ε
private static boolean C() {
    if (input.charAt(index) == 'e') {
        index++;
        if (C()) {
            return true;
        }
    }
    return true; // ε产生式
}

}

输入样例1:

ie*e

输出样例1:

Success

输入样例2:

[iieeeeeeeeeeC].i

输出样例2:

Success

输入样例3:

iieeeeeeeeee

输出样例3:

Erro


原文地址: https://www.cveoy.top/t/topic/hmYG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录