Chomsky格式CFG算法的Java实现

Chomsky格式CFG算法的Java实现,java,context-free-grammar,chomsky-normal-form,Java,Context Free Grammar,Chomsky Normal Form,目标是将伪代码转换为实际工作代码。我想我基本上已经弄明白了,但有些地方不太对劲 我使用的规则是 S -> RT|empty T -> TR|a R => TR|b 以下是伪代码: D == "On input W == WI . ..Wn : 1. If W == e and S -> e is a rule, accept. [handle w == empty case] 2. For i == 1 to n: [examine each substring of

目标是将伪代码转换为实际工作代码。我想我基本上已经弄明白了,但有些地方不太对劲

我使用的规则是

S -> RT|empty
T -> TR|a
R => TR|b
以下是伪代码:

D == "On input W == WI . ..Wn :
1. If W == e and S -> e is a rule, accept. [handle w == empty case]
2. For i == 1 to n: [examine each substring of length 1] 
3.     For each variable A:
4.         Test whether A -> b is a rule, where b == Wi. 
5.         If so,place A in table(i,i). 
6. For l == 2 to n:
7.     For i == 1 to n -l + 1:
8.         Let j == i + l - 1,
9.         For k == i to j -1:
10.            For each rule A \037 BC:
11.            If table(i,k)contains B and table(k + 1,j)contains
               C,put A in table(i,j).
12.If S is in table(l,n), accept.Otherwise, reject.
以下是实际代码:

public class algorithm {

public static void main(String[] args){
    String w = " abab";
    String table[][] = new String[w.length()][w.length()];
    if (w.isEmpty()){
        System.out.println("Accept\n");
    }

    for(int i=1; i<w.length();i++){
        if(w.charAt(i)=='a')
            table[i][i]="R";
        else if(w.charAt(i)=='b')
            table[i][i]="T";
    }
    for(int l=2; l<=w.length();l++){
        for(int i=1; i<w.length()-l+1;i++){
            int j = i+l-1;
            for(int k=i; k<=j-1;k++){
                if(table[i][k].contains("T") && table[k+1][j].contains("R"))
                    table[i][j]="T,R"; //Not sure how to do this part?
                else if(table[i][k].contains("R") && table[k+1][j].contains("T"))
                    table[i][j]="S";

            }
        }

    }
    System.out.println("Finished");
    System.out.println(w);
    for(int i=1;i<w.length();i++){
        for(int j=1;j<w.length();j++){
        System.out.print(table[i][j]+"\t");}
        System.out.println("");

    }
    //System.out.println((table[1][w.length()-1]));
    //if (table[1][w.length()-1].equals("S"))
    //  System.out.println("Accept");
}

}

然而,正如你所知,baba可以从语法中派生出来

发现我做错了什么。首先,我有

 abab
   R    S   S   null    
   null T   T,R S   
   null null    R   S   
   null null    null    T