2016-07-15 4 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 

キーは、この場合2 5 10 3「後順」にツリー構造「INORDER」を作り直すためにスタック操作を使用することである - 括弧なしこれは明確な形である* +

とマシン処理のために容易に読み取ることができます。あなたが興味を持っているなら、私はそれを見ることができます。

関連する問題