Skip to content

Instantly share code, notes, and snippets.

@mxrguspxrt
Created November 19, 2012 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxrguspxrt/4113122 to your computer and use it in GitHub Desktop.
Save mxrguspxrt/4113122 to your computer and use it in GitHub Desktop.
java2-home5.java
import java.util.*;
public class Answer {
public String name;
public Answer firstChild;
public Answer nextSibling;
public static <T extends Object> void p(T s){
System.out.println(s);
}
Answer (String name, Answer firstChild, Answer nextSibling) {
this.name = name;
this.firstChild = firstChild;
this.nextSibling = nextSibling;
}
Answer (String s) {
s = s.trim();
if(s.equals("")) throw new RuntimeException();
this.name = "";
String parts[] = s.split("");
int length = parts.length;
for(int i=0; i<length; i++) {
String part = parts[i].trim();
if(part.equals(",")) {
//
this.nextSibling = new Answer(s.substring(i, length-1));
break;
}
else if(part.equals("(")) {
//
int weight = -1;
for(int j=i+1; j<length; j++) {
if(parts[j].equals("(")) weight -= 1;
if(parts[j].equals(")")) weight += 1;
p(weight);
if(weight==0){
this.firstChild = new Answer(s.substring(i, j-1));
i = j;
break;
}
}
}
else {
//
this.name += part;
}
}
}
public static Answer parseTree (String s) {
return new Answer(s);
}
public String rightParentheticRepresentation() {
String returnString = this.name;
if(this.firstChild!=null) returnString = "("+this.firstChild.rightParentheticRepresentation()+")" + returnString;
if(this.nextSibling!=null) returnString = returnString + "," + this.nextSibling.rightParentheticRepresentation();
return returnString;
}
public String toString() {
String returnString = this.name;
if(this.firstChild!=null) returnString += "("+this.firstChild.toString()+")";
if(this.nextSibling!=null) returnString += ","+this.nextSibling.toString();
return returnString;
}
public static void main (String[] param) {
String s = "+(*(-(2,1),4),/(6,3))";
Answer t = Answer.parseTree (s);
String v = t.rightParentheticRepresentation();
System.out.println (s + " ==> " + v); // A(B,C) ==> (B,C)A
System.out.println(t.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment