刷题208. Implement Trie (Prefix Tree)

一、题目说明

题目208. Implement Trie (Prefix Tree),实现trie,包括insert、search、startsWith。

二、我的解答

Trie树,又叫“字典树”,“前缀树”。实现代码如下:

class Trie{
	public:
		Trie(){
			isEnd = false;
			memset(next,0,sizeof(next)); 
		}
		~Trie(){
			for(int i=0;i<26;i++){
				if(next[i] == NULL){
					continue;
				}else{
					delete(next[i]);
					next[i] = NULL;
				}
			}
		}
		void insert(string word){
			Trie* node = this;
			for(char c: word){
				int cur = c - 'a';
				if(node->next[cur] == NULL){
					node->next[cur] = new Trie();
				}
				node = node->next[cur];
			}
			node->isEnd = true;
		}
		bool search(string word){
			Trie* node = this;
			for(char c: word){
				int cur = c - 'a';
				node = node->next[cur];
				if(node == NULL){
					return false;
				}
			}
			return node->isEnd;
		}
		
		bool startsWith(string prefix){
			Trie* node = this;
			for(char c: prefix){
				int cur = c - 'a';
				node = node->next[cur];
				if(node == NULL){
					return false;
				}
			}
			return true;
		}

	private:
		bool isEnd;
		Trie* next[26];
};

性能如下:

Runtime: 84 ms, faster than 54.43% of C++ online submissions for Implement Trie (Prefix Tree).
Memory Usage: 45.9 MB, less than 20.00% of C++ online submissions for Implement Trie (Prefix Tree).

三、优化措施

posted @ 2020-04-04 18:25  siwei718  阅读(92)  评论(0编辑  收藏  举报