LeetCode——208. Implement Trie (Prefix Tree)

Description

Implement a trie with insert, search, and startsWith methods.

Example

Trie trie = new Trie();

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

Note

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

Solution 1(C++)

class TrieNode{
public:
	staic const int NODE_SIZE = 26;
	TrieNode* child[NODE_SIZE];
	bool isExist;

	TrieNode(){
		for(int i=0; i<NODE_SIZE; i++){
			child[i] = NULL;
		}
		isExist = false;
	}

	TrieNode(char c){
		for(int i=0; i<NODE_SIZE; i++){
			if(c-'a' == i) child[i] = new TrieNode();
		}
		isExist = false;
	}
};

class Trie{
public:
	Trie(){
		root = new TrieNode();
		root->isExist = true;
	}
	
	~Trie(){
		Destory(node);
	}
	
	void insert(string word){
		TrieNode* temp = root;
		for(int i=0; i<word.size(); i++){
			if(temp->child[word[i]-'a'] == NULL){
				temp->child[word[i]-'a'] = new TrieNode();
			}
			temp = temp->child[word[i]-'a'];
		}
		temp->isExist = true;
	}

	bool search(string word){
		if(word == "") return true;
		TrieNode* temp = root;
		for(int i=0; i<word.size(); i++){
			if(temp->child[word[i]-'a'] == NULL) return false;
			temp = temp->child[word[i]-'a'];
		}
		return temp != NULL && temp->isExist == true;
	}

	bool startsWith(string prefix){
		if(prefix == "") return true;
		TrieNode* temp = root;
		for(int i=0; i<prefix.size(); i++){
			if(temp->child[prefix[i]-'a'] == NULL) return false;
			temp = temp->child[prefix[i]-'a'];
		}
		return temp != NULL;
	}
	
	void Destory(TreeNode* node)}{
		for(int i=0; i<NODE_SIZE; I++){
			if(node->child[i] == NULL) Destory(node->child[i]);
		}
	}

private:
	TrieNode* root;
};

算法分析

这道题考察的是字典树。弄明白字典树的基本含义,这道题目就不难。

程序分析

注意,虽然对解题没有什么帮助,但是还要注意,析构函数与内存的释放。养成一个好习惯,毕竟用了C++。

你可能感兴趣的:(LeetCode,LeetCode)