Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

构建字典树

class TrieNode {
    char c;
    HashMap<Character, TrieNode> children=new HashMap<Character, TrieNode>();
    boolean hasWord;
    public TrieNode(){
        
    }
    public TrieNode(char c){
        this.c=c;
    }
}

public class Trie{
    private TrieNode root;
    public Trie(){
        root=new TrieNode();
    }
    
    public void insert(String word){
        TrieNode cur=root;
        HashMap<Character, TrieNode> curchildren=root.children;
        char[] wordArray=word.toCharArray();
        for(int i=0;i<wordArray.length;i++){
            char wc=wordArray[i];
            if(curchildren.containsKey(wc)){
                cur=curchildren.get(wc);
            }else{
                TrieNode newNode=new TrieNode(wc);
                curchildren.put(wc, newNode);
                cur=newNode;
            }
            
            curchildren=cur.children;
            if(i==wordArray.length-1){
                cur.hasWord=true;
            }
        }
    }
    
    public boolean search(String word){
        if(searchWordNodePos(word)==null){
            return false;
        }else if(searchWordNodePos(word).hasWord){
            return true;
            
        }else return false;
    }
    
    public boolean startsWith(String prefix){
        if(searchWordNodePos(prefix)==null){
            return false;
        }else return true;
    }

    private TrieNode searchWordNodePos(String s) {
        // TODO Auto-generated method stub
        HashMap<Character, TrieNode> children=root.children;
        TrieNode cur=null;
        char[] sArray=s.toCharArray();
        for(int i=0;i<sArray.length;i++){
            char c=sArray[i];
            if(children.containsKey(c)){
                cur=children.get(c);
                children=cur.children;
            }else{
                return null;
            }
        }
        
        return cur;
    }
    
    
    
}


// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
View Code

参考:http://blog.csdn.net/yangliuy/article/details/46287671

        http://www.cnblogs.com/huangxincheng/archive/2012/11/25/2788268.html

posted on 2015-06-14 13:38  gone~with~wind  阅读(197)  评论(0编辑  收藏  举报