LintCode 442:Implement Trie
来源:互联网 发布:js自定义全局函数 编辑:程序博客网 时间:2024/06/06 01:46
class TrieNode {public: // Initialize your data structure here. TrieNode* children[26]; bool flag;//check if it's the end of a word. TrieNode() :flag(0){ for(int i=0;i<26;i++) children[i]=NULL; }};class Trie { TrieNode* insertNode(char tmp,TrieNode* parent){ int index=tmp-97; if(!parent->children[index]) parent->children[index]=new TrieNode(); return parent->children[index]; } int ifStartWith(string word){ char c=word[0]; int index=c-97; int stringLength=word.length(); int i; TrieNode* child; if(!root->children[index]) return 0; else child=root->children[index]; for(i=1;i<stringLength;i++){ index=word[i]-97; if(!child->children[index]) return 0; child=child->children[index]; } if(child->flag) return 1;//exists the word; else return -1;//only exists the subword. }public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(string word) { int stringLength=word.length(); if(!stringLength) return; int i; TrieNode* child=insertNode(word[0],root); for(i=1;i<stringLength;i++){ child=insertNode(word[i],child); } child->flag=1; } // Returns if the word is in the trie. bool search(string word) { if(ifStartWith(word)==1) return 1; return 0; } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(string prefix) { if(ifStartWith(prefix)) return 1; return 0; }private: TrieNode* root;};
0 0
- LintCode 442:Implement Trie
- [Lintcode]Implement Trie 字典树
- implement-trie
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- springMVC--注解
- 第六天、使用ServerSocket建立一个服务端
- 算法导论第三章总结
- class对象及类的初始化过程
- 单虚拟机nginx-rtmp-module直播带宽测试
- LintCode 442:Implement Trie
- encodeURIComponent编码与解码--java
- java对象在内存中的分配
- HDU 1568 Fibonacci 公式 *
- 1031. Hello World for U (20)
- maven 制作 alipay-sdk-java包到本地仓库
- 通过Zookeeper动态感知服务器上下线[案例]
- LinkedHashMap详解
- HTML5 & CSS3初学者指南(4) – Canvas使用