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);
 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章