[leetcode] 211 Add and Search Word - Data structure design
2015-09-04 01:06
531 查看
因为给定了a-z这个范围,并且字符串的添加和查找符合Trie的常用方法,因此考虑使用Trie这种数据结构。
然后和普通的Trie不同的是,要匹配正则表达式中的“.”,也就是说在这一层是无法判断沿着拿个结点向下走的,所以要循环这一层的结点,只有这一层所有结果失败后才能返回false,剩下的递推。所以我们采取Trie+回溯法。
代码中的searchHelp函数是专门用于回溯的,要求会回溯的掌握比较好。
然后和普通的Trie不同的是,要匹配正则表达式中的“.”,也就是说在这一层是无法判断沿着拿个结点向下走的,所以要循环这一层的结点,只有这一层所有结果失败后才能返回false,剩下的递推。所以我们采取Trie+回溯法。
代码中的searchHelp函数是专门用于回溯的,要求会回溯的掌握比较好。
class Trie { public: Trie *next[26]; int flag; Trie():flag(0) { for(int i=0;i<26;i++) next[i]=0; } }; class WordDictionary { private: Trie *root; public: WordDictionary(){ root=new Trie(); } // Adds a word into the data structure. void addWord(string word) { Trie *p=root; for(int i=0;i<word.length();i++) { if(p->next[word[i]-'a']==NULL) { p->next[word[i]-'a']=new Trie(); } p=p->next[word[i]-'a']; } p->flag=1; } // Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. bool search(string word) { int n=word.length(); return searchHelp(word,0,root,n); } bool searchHelp(string &word,int cur,Trie *root,int n) { if(root==NULL) return false; if(cur==n) { if(root->flag) return true; return false; } if(word[cur]=='.') { for(int i=0;i<26;i++) { if(root->next[i]) if(searchHelp(word,cur+1,root->next[i],n)) return true; // return searchHelp(word,cur+1,root->next[i],n) // is wrong.because maybe another node is ok } } else { int temp=word[cur]-'a'; if(root->next[temp]) return searchHelp(word,cur+1,root->next[temp],n); return false; } // return false; } };
相关文章推荐
- 规则引擎实战篇-------银行贷款业务处理2
- Linux-3.5 下WiFi移植
- [HDOJ1022]Train Problem I
- javaSE基础编程——字符串面试题(找出一个带多个下划线的字符串中第二个字符串后的字符)
- 将这两个字符串交叉连接。
- 深入理解C++的动态绑定和静态绑定
- C++ map
- C++ map
- 关于实现一个小网站
- C++ template
- c++ namespace
- 笔试题:求二叉树第n层的节点数。
- C++ template
- c++ namespace
- javaSE基础编程——方法的重载(汽车类)
- Android应用的定时通知实现
- latex 学习
- Android开发利用Volley框架下载和缓存网络图片
- GDI+学习笔记5-设备环境DC的概念
- append()和appendTo()的区别