leetcode-208-实现Trie (前缀树)-java

题目及测试

package pid208;
/* 实现 Trie (前缀树)

实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

示例:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // 返回 true
trie.search("app");     // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");   
trie.search("app");     // 返回 true

说明:

    你可以假设所有的输入都是由小写字母 a-z 构成的。
    保证所有输入均为非空字符串。



*/
public class main {
	
	public static void main(String[] args) {
		Trie trie = new Trie();

		trie.insert("apple");
		System.out.println(trie.search("apple"));   // 返回 true
		System.out.println(trie.search("app"));     // 返回 false
		System.out.println(trie.startsWith("app")); // 返回 true
		trie.insert("app");   
		System.out.println(trie.search("app"));     // 返回 true
	}


}

解法1(成功,40ms,极快)

TrieNode类,有isEnd字段,TrieNode[] nodes= new TrieNode[26]

Trie里有TrieNode类型的root,如果确实有一个字符 abc 那么root.nodes[0]不为null,而且最后一个nodes[2].isEnd为true

插入时,就node.nodes[now-a] = new TrieNode(),新增一个节点,最后node.isEnd = true

查找时,不断node = node.nodes[now-a],如果没有,则返回false,如果都有,就看最后node.isEnd是否为true

package pid208;


class Trie {
	
	class TrieNode{
		boolean isEnd = false;
		TrieNode[] nodes= new TrieNode[26];
	}
	// 如果确实有一个字符 abc 那么root.nodes[0]不为null,而且最后一个nodes[2].isEnd为true
	TrieNode root = new TrieNode();

    /** Initialize your data structure here. */
    public Trie() {

    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
    	char[] chars=word.toCharArray();
    	TrieNode node = root;
    	for(int i=0;i<chars.length;i++){
    		char now=chars[i];
    		if(node.nodes[now-a] == null){
    			node.nodes[now-a] = new TrieNode();
    		}
    		node = node.nodes[now-a];   		
    	}
    	node.isEnd = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
    	char[] chars=word.toCharArray();
    	TrieNode node = root;
    	for(int i=0;i<chars.length;i++){
    		char now=chars[i];
    		if(node.nodes[now-a] == null){
    			return false;
    		}else{
    			node = node.nodes[now-a];
    		}
    	}
    	if(node.isEnd == true){
    		return true;
    	}else{
    		return false;
    	}    	
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
    	char[] chars=prefix.toCharArray();
    	TrieNode node = root;
    	for(int i=0;i<chars.length;i++){
    		char now=chars[i];
    		if(node.nodes[now-a] == null){
    			return false;
    		}else{
    			node = node.nodes[now-a];
    		}
    	}
    	return true; 	
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */
经验分享 程序员 微信小程序 职场和发展