|
import java.io.BufferedReader; |
|
import java.io.IOException; |
|
import java.io.InputStreamReader; |
|
import java.util.Map; |
|
import java.util.TreeMap; |
|
import java.util.regex.Pattern; |
|
|
|
|
|
public class Biostar52895 |
|
{ |
|
private static class Node |
|
{ |
|
Map<String,Node> children=new TreeMap<String, Biostar52895.Node>(); |
|
|
|
void fill(String tokens[],int index) |
|
{ |
|
Node c=children.get(tokens[index]); |
|
if(c==null) |
|
{ |
|
c=new Node(); |
|
this.children.put(tokens[index],c); |
|
} |
|
if(index+1< tokens.length) c.fill(tokens, index+1); |
|
} |
|
void printChildren() |
|
{ |
|
boolean first=true; |
|
System.out.print("("); |
|
for(String childName:this.children.keySet()) |
|
{ |
|
if(!first) System.out.print(","); |
|
first=false; |
|
Node c=this.children.get(childName); |
|
c.print(childName); |
|
} |
|
System.out.print(")"); |
|
} |
|
void print(String myName) |
|
{ |
|
if(!this.children.isEmpty()) |
|
{ |
|
printChildren(); |
|
} |
|
System.out.print(myName); |
|
} |
|
} |
|
private Node root=new Node(); |
|
|
|
private void parse(BufferedReader in) throws IOException |
|
{ |
|
Pattern semicolon=Pattern.compile("[;]"); |
|
String line; |
|
while((line=in.readLine())!=null) |
|
{ |
|
if(line.isEmpty()) continue; |
|
String tokens[]=semicolon.split(line); |
|
root.fill(tokens, 0); |
|
} |
|
|
|
} |
|
private void print() |
|
{ |
|
this.root.printChildren(); |
|
System.out.println(";"); |
|
} |
|
|
|
public static void main(String[] args) throws IOException |
|
{ |
|
Biostar52895 app=new Biostar52895(); |
|
app.parse(new BufferedReader(new InputStreamReader(System.in))); |
|
app.print(); |
|
} |
|
|
|
} |
You may also want to take a look at this: http://www.biostars.org/post/show/13452/parsing-ncbi-taxonomic-tree/#13464