开发者

search in tries in java

开发者 https://www.devze.com 2023-02-28 01:33 出处:网络
hi i 开发者_StackOverflow中文版have a project that i need to implement a dictionary by tries ... but now i can\'t implement search method .... my code is here

hi i 开发者_StackOverflow中文版have a project that i need to implement a dictionary by tries ... but now i can't implement search method .... my code is here

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);
    }
}

in this code i have error in else statement!!!! i want to replace the root by one of the children that it's value is similar to the first character of key(temp) but i can't do this in "else statement" ... and why i can't access to the value of children??


Ok, root is TriesNode type, but root.children is not the same type, that's the problem. You can't assign values from different types. You must declare a variable of root.children type and then assign that value. To assign directly the value of root.children to root you must do:

root.Add(root.children)

more or less...


root = root.children.value.equals(temp) doesnt assign root.child to root rather it assigned true or false to root because your checking if it equals temp or not.

also java doesnt allow you to have if statement that returns value of different types from an if statemen.

this will return the final root in the chain, is that the value your looking for ?

try

        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       
}      
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号