首页 笔记 图片 查字 
所属分类:其它
关键词: LeetCode 前缀 Java
浏览:32
内容:


代码:

// 前缀树
public class PrefixTrie {

    public static void main(String[] args) {
        PrefixTrie prefixTrie=new PrefixTrie();
        prefixTrie.insert("apps");
        prefixTrie.insert("apply");
        prefixTrie.insert("apple");

        boolean app = prefixTrie.search("app");
        System.out.println(app);

        app = prefixTrie.search("apps");
        System.out.println(app);

        app = prefixTrie.startWith("apple");
        System.out.println(app);

        app = prefixTrie.startWith("acc");
        System.out.println(app);
    }

    private class TrieNode{
        private  boolean isEnd;
        private TrieNode[] next;
        public TrieNode(){
            isEnd=false;
            next=new TrieNode[26];
        }
    }

    private TrieNode root;

    public PrefixTrie(){
        root = new TrieNode();
    }

    public void insert(String word){
        TrieNode node=root;
        for(int i=0, l=word.length(), n; i<l;i++){
            n = word.charAt(i) - 'a';
            if(node.next[n]==null){
                node.next[n]=new TrieNode();
            }
            node = node.next[n];
        }
        node.isEnd=true;
    }

    public boolean search(String word){
        TrieNode node=root;
        for(int i=0, l=word.length(), n; i<l;i++){
            n = word.charAt(i) - 'a';
            if(node.next[n]==null){
                return false;
            }
            node = node.next[n];
        }
        return node.isEnd;
    }

    public boolean startWith(String word){
        TrieNode node=root;
        for(int i=0, l=word.length(), n; i<l;i++){
            n = word.charAt(i) - 'a';
            if(node.next[n]==null){
                return false;
            }
            node = node.next[n];
        }
        return true;
    }
}