2016-07-15 2 views
-1

현재 newick 형식을 연구 중입니다. https://en.wikipedia.org/wiki/Newick_format. 나는Java를 사용하여 newick 계층 구조 문자열을 계층 적 JSON 객체로 변환

JSONObject tree = { 
    name: 'PQR', 
    children: [{ 
    name: 'ABC' 
    }, { 
    name: 'DEF', 
    children: [{ 
     name: 'STU' 
    }, { 
     name: 'VWX' 
    }] 
    }, { 
    name: 'MNO', 
    children: [{ 
     name: 'GHI' 
    }, { 
     name: 'JKL' 
    }] 
    }] 
} 

같은 계층 JSON 객체로이 문자열을 변환하는 방법

(ABC,(STU,VWX)DEF,(GHI,JKL)MNO)PQR; 

이 내가 시도 것을이지만 채우기하는 방법의 더 생각하지 수있는 나무의 newick 문자열을 루트 노드의 자식

import java.util.ArrayList; 
import java.util.List; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

public class Series1 { 

    public static void main(String[] args) throws JSONException 
    { 
    String data="(ABC,(STU,VWX,EFG)DEF,YZA,HIJ,(GHI,JKL)MNO,BCD)PQR"; 
    JSONObject tree=new JSONObject(); 
    tree.put("name",data.substring(data.lastIndexOf(")")+1,data.length())); 
    tree.put("children", getChildren(data.substring(1,data.lastIndexOf(")")))); 
    } 
    public static JSONArray getChildren(String children) throws JSONException 
    { 
     JSONArray childrenArray=new JSONArray(); 
     List<Integer> commaIndexList=new ArrayList<Integer>(); 
     List<String> childrenStringList=new ArrayList<String>(); 
     for (int index = children.indexOf(",");index >= 0;index = children.indexOf(",", index + 1)) 
      { 
      if(children.substring(index+1, index+2).equalsIgnoreCase("(")) 
       { 
        commaIndexList.add(index); 
        System.out.println(index); 
       } 
      } 
     childrenStringList.add(children.substring(0, commaIndexList.get(0))); 
     childrenStringList.add(children.substring(commaIndexList.get(commaIndexList.size()-1)+1)); 
     for(int i=0;i<commaIndexList.size()-1;i++) 
     { 
      childrenStringList.add(children.substring(commaIndexList.get(i)+1, commaIndexList.get(i+1))); 
     } 
     for(String childrenString:childrenStringList) 
     { 
      JSONObject childObject=new JSONObject(); 
      if(childrenString.lastIndexOf(")")>0) 
      { 
       childObject.put("name", childrenString.substring(childrenString.lastIndexOf(")")+1)); 
       childObject.put("children", getChildren(childrenString.substring(childrenString.indexOf("(")+1,childrenString.lastIndexOf(")")))); 
      } 
      else 
      { 
       childObject.put("name",childrenString); 
      } 
      childrenArray.put(childObject); 


     } 

     return childrenArray; 
    } 

} 

답변

-1

이 문제는 수학적 표현을 평가하는 것과 유사합니다. 2 + 5 * (10-3) =?

+ 
2  * 
    5  - 
      10 3 

키는이 경우에 'postorder'로 트리 '중위'구조를 다시 만드는 스택 동작을 사용하는 2 5 10 - 3 * +

이것은 괄호없이 일정한 형태이며 기계 가공을 위해 쉽게 읽을 수 있습니다. 당신이 관심이 있다면, 나는 그것을 볼 수 있습니다.