1

嗨,我有一个项目,我需要通过尝试来实现字典......但现在我无法实现搜索方法......我的代码在这里

public class TriesNode {
String value;
ArrayList<TriesNode> children = new ArrayList<TriesNode>();


String findNode(TriesNode root , String key ){
    for (int i=0 ; i<key.length() ; ++i){
        char temp= key.charAt(i);
        if ( !(root.children.equals(temp)))
            return null;
        else
            root = root.children.value.equals(temp);
    }
}

在这段代码中,我在 else 语句中有错误!!!!我想用其中一个孩子替换根,它的值类似于 key(temp) 的第一个字符,但我不能在“else statement”中这样做......以及为什么我无法访问该值孩子的??

4

2 回答 2

0

好的,root 是 TriesNode 类型,但是 root.children 不是同一个类型,这就是问题所在。您不能分配来自不同类型的值。您必须声明一个 root.children 类型的变量,然后分配该值。要将 root.children 的值直接分配给 root,您必须执行以下操作:

root.Add(root.children)

或多或少...

于 2011-04-20T07:17:16.363 回答
0

root = root.children.value.equals(temp) 没有将 root.child 分配给 root,而是将 true 或 false 分配给 root,因为您检查它是否等于 temp。

java也不允许你有从if语句返回不同类型值的if语句。

这将返回链中的最终根,这是您要寻找的值吗?

尝试

        TriesNode findFinalRoot(TriesNode root, String key){
                      if(key.length() == 0 )
              return root;
        for(int x = 0 ; x <root.children.lenth(); x++)

          if (key.charAt(0) == root.children.get(x).charAt(0)){
             findFinalRoot(root,key.subString(1)); // here you loss first character       
}      
于 2011-04-20T07:19:15.647 回答