leetcode Add and Search Word - Data structure design
2015-05-30 22:38
656 查看
题目
Design a data structure that supports the following two operations:void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
For example:
addWord(“bad”)
addWord(“dad”)
addWord(“mad”)
search(“pad”) -> false
search(“bad”) -> true
search(“.ad”) -> true
search(“b..”) -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
题目来源:https://leetcode.com/problems/add-and-search-word-data-structure-design/
分析
关于字典树(trie tree)的概念和分析见:/article/2077132.html主要挑战性在于’.’的匹配。遇到一个’.’就得匹配当前next[]数组里面所有的有效分支。用个递归函数,递归匹配吧。
代码
[code]class TrieNode{ public: int flag; TrieNode* next[26]; TrieNode(){ flag = 0; for(int i = 0; i < 26; i++){ next[i] = NULL; } } }; class WordDictionary { private: TrieNode *root; public: WordDictionary(){ root = new TrieNode(); } // Adds a word into the data structure. void addWord(string word) { TrieNode* p = root; int len = word.length(); if(len <= 0) return; for(int i = 0; i < len; i++){ int d = word.at(i) - 'a'; if((p->next)[d] == NULL){ p->next[d] = new TrieNode(); p->next[d]->flag = 0; } p = p->next[d]; } 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 searchHelp(string word, struct TrieNode *root){ struct TrieNode *p = root; int len = word.length(); if(len <= 0){//为了匹配字符串中字符'.'是最后一个字符的情形。 if(p->flag == 1) return true; else return false; } if(root == NULL) return false; for(int i = 0; i < len; i++){ if(word.at(i) == '.'){ bool result = false; for(int j = 0; j < 26; j++){ if(p->next[j] != NULL){ result = result || searchHelp(word.substr(i+1), p->next[j]); } } return result; } else { int d = word.at(i) - 'a'; if(p->next[d] == NULL) return false; p = p->next[d]; } } if(p->flag == 1) return true; else return false; } bool search(string word) { int len = word.length(); if(len <= 0) return true; return searchHelp(word, root); } }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
相关文章推荐
- 2015年百度之星初赛(1) --- D KPI
- 汉诺塔的C语言实现
- LSB 脚本规范简介
- android中通过JNI读取Bitmap文件,并调用opencv进行处理
- javase 小知识2
- C++ 虚函数
- 划分树模板
- 飞机大战-MyPlane自己飞机的实现
- jQuery基础选择器
- 专家解析云部署时应避免的20个错误
- 我的Cocos2d-x学习笔记(十三)CCLabelTTF、CCLabelAtlas、CCLabelBMFont
- Launcher及Statusbar学习小结
- PLSQL设置显示中文的字符集
- 数据库事务
- kb-07专题线段树-02--单点修改,区间最值
- ubuntu下c语言hello world
- 关于在linux下用java程序执行linux命令的权限问题
- Solving "Vietnam snake" puzzle with constraint logic programming
- 【十三】队列的链式存储结构
- Fuel 30 分钟快速安装OpenStack(转)