• 刷题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).
    

    三、优化措施

    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    Swift网络库Alamofire的导入
    iOS书摘之Objective-C编程之道 iOS设计模式解析
    Crash日志分析
    自动布局库--Masonry使用
    Xcode Ghost
    Xcode8-beat升级需谨慎
    UIView剖析之Draw、Size、Layout方法
    Xcode警告忽略
    属性(property)与成员变量(ivar)
    sql server分页存储过程
  • 原文地址:https://www.cnblogs.com/siweihz/p/12290880.html
Copyright © 2020-2023  润新知