컴파일 원리 LL1 문법First 집합 알고리즘 실현
8280 단어 first
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<String, Set<Character>> first = new TreeMap<String, Set<Character>>();
private Map<String, String[]> mp = null;
public First(Map<String, String[]> mp) {
super();
this.mp = mp;
}
public Map<String, Set<Character>> getFirstSet(){
return first;
}
private Set<Character> findFirst(String curNode, String[] rightNodes){
if(first.containsKey(curNode)) return first.get(curNode);
Set<Character> st = new TreeSet<Character>();
for(int i=0; i<rightNodes.length; ++i){
for(int j=0; j<rightNodes[i].length(); ++j){
String nextNode = ""+rightNodes[i].charAt(j);
if(!mp.containsKey(nextNode)){//
st.add(nextNode.charAt(0));
break;
}
else{//
if(j+1<rightNodes[i].length() && rightNodes[i].charAt(j+1)=='\''){
nextNode += rightNodes[i].charAt(j+1);
++j;
}
if(mp.containsKey(nextNode)){
Set<Character> 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<String, Set<Character>> entry : first.entrySet()){
content += entry.getKey() + " : " + entry.getValue() + "
";
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<String, String[]> mp = new LinkedHashMap<String, String[]>();
try{
for(int i=0; i<rightLinearGrammar.length; ++i){
String split1[] = rightLinearGrammar[i].split("->");
String split2[] = split1[1].split("\\|");
mp.put(split1[0], split2);
}
} catch(Exception e){
e.printStackTrace();
System.out.println(" !");
}
new First(mp).firstKernealCode();
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
흥미로운 자바 퍼즐 - 인스턴스 이니셜라이저아래 Java 코드의 출력이 무엇인지 추측할 수 있습니까? 가능한 출력 목록은 다음과 같습니다. 정답은 (3) Feathers 설명 인스턴스 이니셜라이저는 한 쌍의 중괄호({ 및 }) 사이에 정의된 코드 블록입니다....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.