我试图将GWT中的字符串解析为Object结构。不幸的是我无法做到这一点。
示例字符串:
"(node1(node2(node3) (node4)) (node5))"
"node1"
有2个孩子:"node2"
和"node5"
"node2"
有2个孩子:"node3"
和"node4"
对象可以是“节点”,带有子节点。 任何有关这方面的帮助将不胜感激。
答案 0 :(得分:3)
我可以为您提供伪代码。我相信下面的算法会有效,但如果你发现它有任何问题,请告诉我。
Create a root node called nodeRoot.
current_node = nodeRoot
For each char in the string:
if the char is '('
add a child node to current_node
parse the string (after the '(' char) to fetch the name of the node
current_node = the newly added child node
else if the char is ')'
current_node = parent of current_node
要跟踪父母,您可以使用堆栈。
答案 1 :(得分:0)
我很无聊所以我把一些代码敲了一下。
private static class ObjectTree {
private Set<ObjectTree> children = new LinkedHashSet();
private ObjectTree parent = null;
private String text = null;
private int level = 0;
public ObjectTree() {
this(null);
}
public ObjectTree(ObjectTree parent) {
this(parent, 0);
}
public ObjectTree(ObjectTree parent, int level) {
this.parent = parent;
this.level = level;
}
public void addChild(ObjectTree child) {
children.add(child);
}
public void parse(String s) {
int ix = s.indexOf("(");
if (ix > 0)
text = s.substring(0, ix);
else if (ix <= 0)
text = s;
int iy = ix + 1;
int count = 1;
if (ix == -1)
return;
while (iy < s.length()) {
if (s.charAt(iy) == ')')
count--;
else if (s.charAt(iy) == '(')
count++;
if (count == 0) {
String newString = s.substring(ix + 1, iy);
ObjectTree newChild = new ObjectTree(this, level + 1);
addChild(newChild);
newChild.parse(newString);
ix = s.indexOf('(', iy);
count++;
iy = ix;
}
iy++;
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(StringUtils.repeat("\t.", level)).append(text).append(" :\n");
for (ObjectTree child : children) {
sb.append(StringUtils.repeat("\t", level)).append("\t").append(child.toString()).append("\n");
}
if (!children.isEmpty())
sb.append("\n");
return sb.toString();
}
}
你这样称呼它:
ObjectTree root = new ObjectTree();
root.parse("(node1(node2(node3) (node4)) (node5))");
System.out.println(root.toString());
得到:
(node1(node2(node3) (node4)) (node5)) :
.node1 :
. .node2 :
. . .node3 :
. . .node4 :
. .node5 :