本文共 1570 字,大约阅读时间需要 5 分钟。
import java.util.LinkedHashMap;import java.util.Map;import java.util.Set;import java.util.TreeMap;import java.util.TreeSet;public class First { private Map> first = new TreeMap >(); private Map mp = null; public First(Map mp) { super(); this.mp = mp; } public Map > getFirstSet(){ return first; } private Set findFirst(String curNode, String[] rightNodes){ if(first.containsKey(curNode)) return first.get(curNode); Set st = new TreeSet (); for(int i=0; i tmpSt = findFirst(nextNode, mp.get(nextNode)); st.addAll(tmpSt); if(!tmpSt.contains('$')) break; } } } } first.put(curNode, st); return st; } public String firstKernealCode(){ String content = ""; for(String leftNode : mp.keySet()){ String[] rightNodes = mp.get(leftNode); findFirst(leftNode, rightNodes); } //打印first集合 System.out.println("First集合如下:"); for(Map.Entry > entry : first.entrySet()){ content += entry.getKey() + " : " + entry.getValue() + "\n"; System.out.println(entry.getKey() + " : " + entry.getValue()); } return content; } public static void main(String[] args){// String[] rightLinearGrammar = {// "E->TE\'",// "E\'->+TE\'|$",// "T->FT\'",// "T\'->*FT\'|$",// "F->(E)|i"// }; String[] rightLinearGrammar = { "S->ABc", "A->a|$", "B->b" }; Map mp = new LinkedHashMap (); try{ for(int i=0; i "); String split2[] = split1[1].split("\\|"); mp.put(split1[0], split2); } } catch(Exception e){ e.printStackTrace(); System.out.println("右线性文法错误!"); } new First(mp).firstKernealCode(); }}
转载地址:http://usflx.baihongyu.com/