leetcode 211. Add and Search Word - Data structure design Trie树
2016-01-11 00:10
441 查看
题目链接
写一个数据结构, 支持两种操作。 加入一个字符串, 查找一个字符串是否存在。查找的时候, '.'可以代表任意一个字符。
显然是Trie树, 添加就是正常的添加, 查找的时候只要dfs查找就可以。 具体dfs方法看代码。
写一个数据结构, 支持两种操作。 加入一个字符串, 查找一个字符串是否存在。查找的时候, '.'可以代表任意一个字符。
显然是Trie树, 添加就是正常的添加, 查找的时候只要dfs查找就可以。 具体dfs方法看代码。
struct node { node *next[26]; int idEnd; node() { memset(next, NULL, sizeof(next)); idEnd = 0; } }; class WordDictionary { public: // Adds a word into the data structure. node *root = new node(); void addWord(string word) { node *p = root; int len = word.size(); for(int i = 0; i<len; i++) { if(p->next[word[i]-'a'] == NULL) p->next[word[i]-'a'] = new node(); p = p->next[word[i]-'a']; } p->idEnd = 1; return ; } int dfs(string word, int pos, node *p) { //pos是代表当前是在哪一位。 if(pos == word.size()) return p->idEnd; int len = word.size(); for(int i = pos; i<len; i++) { if(word[i] == '.') { for(int j = 0; j<26; j++) { if(p->next[j] == NULL) continue; if(dfs(word, pos+1, p->next[j])) return 1; } return 0; } else if(p->next[word[i]-'a'] != NULL) { return dfs(word, pos+1, p->next[word[i]-'a']); } else { return 0; } } } // 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) { return dfs(word, 0, root); } };
相关文章推荐
- Stanford CoreNLP开源项目的3种编译和运行方式[1]
- 【ORACLE】Oracle 11g数据库的安装图解和配置EM(网页管理)
- javascript遍历对象属性和方法
- Linux Epoll介绍和程序实例
- Java每日解惑
- mysql导入导出数据中文乱码解决方法小结(1、navicat导入问题已解决,创建连接后修改连接属性,选择高级->将使用Mysql字符集复选框去掉,下拉框选择GBK->导入sql文件OK;2、phpmyadmin显示乱码的问题也解决,两步:1.将sql文件以utf8的字符集编码另存,2.将文件中sql语句中的字段字符集编码改成utf8,导入OK)
- 10进制转2进制(递归)
- Oracle学习笔记:图形管理工具 EM 的使用
- jquery中checkbox选择和全选
- 关于 swift 的图片多选问题
- mysq llimit 优化100万数据
- Linux运维01 计划任务
- Android中Canvas绘图之PorterDuffXfermode使用及工作原理详解
- ICANN 推迟批准 .Org 交易
- Android 5.1 OTA包编译错误
- 基于Python实现文件大小输出
- PHP简单开启curl的方法(测试可行) 原创
- 在WordPress中获取数据库字段内容和添加主题设置菜单
- 在WordPress的后台中添加顶级菜单和子菜单的函数详解
- WordPress后台中实现图片上传功能的实例讲解