【Hihocoder】1014 : Trie树
2016-06-17 12:08
288 查看
问题:http://hihocoder.com/problemset/problem/1014
给定一个字符串字典dict,输入字符串str, 要求从dict中找出所有以str为前缀的字符串个数。
构建Trie树:
1) 一个节点有多个子节点。用vector<Node*> nexts 存储。
2) 两个字符串的相同前缀部分共用同一条路径。
3) 每个节点包含计数变量 cnt, 表示有多少个字符串共用该节点
复杂度分析:
假定dict中的字符串个数 n, 字符串的长度 l
1)建树:O(n^2*l)
2) 查找:O(n*l)
源码:
View Code
给定一个字符串字典dict,输入字符串str, 要求从dict中找出所有以str为前缀的字符串个数。
构建Trie树:
1) 一个节点有多个子节点。用vector<Node*> nexts 存储。
2) 两个字符串的相同前缀部分共用同一条路径。
3) 每个节点包含计数变量 cnt, 表示有多少个字符串共用该节点
复杂度分析:
假定dict中的字符串个数 n, 字符串的长度 l
1)建树:O(n^2*l)
2) 查找:O(n*l)
源码:
#include <iostream> #include <vector> #include <string> using namespace std; //node structure in Trie tree struct Node { Node(char _chr = -1){chr = _chr; cnt = 0;} char chr; vector<Node*> nexts; int cnt;//how many strings pass current node }; int main() { Node* root = new Node;//root of dictornary Node* current; vector<Node*> v_current; int cnt, vsize, i, j, strLen; string str; //create Trie tree cin>>cnt; while(cnt-- > 0) { cin>>str; strLen = str.length(); current = root; for(i = 0; i < strLen; i++) { v_current = current->nexts; vsize = v_current.size(); //try to find str[i] in current tree for(j = 0; j < vsize; j++) { if(v_current[j]->chr == str[i]) break; } if(j == vsize)//not found, create a new node { Node* tmp = new Node(str[i]); current->nexts.push_back(tmp); } current = current->nexts[j]; current->cnt++;//increase count of current node } } cin>>cnt; while(cnt-- > 0) { cin>>str; strLen = str.length(); current = root; for(i = 0; i < strLen; i++) { v_current = current->nexts; vsize = v_current.size(); for(j = 0; j < vsize; j++) if(v_current[j]->chr == str[i]) break; if(j == vsize)//not found { cout<<'0'<<endl; break; } current = v_current[j]; } if(i == strLen) cout<<current->cnt<<endl; } return 0; }
View Code
相关文章推荐
- 编写高性能JavaScript【转】
- Activity生命周期,数据传递,启动模式详解
- Angular2 中的依赖注入
- 程序员的恶性循环
- 每日一linux命令(15)-------tail
- Android事件的分发机制详解
- Android开发之为textView添加下划线,中划线等
- 切实解决socket连接掉线检测
- 紧跟时代精华的段子
- Spring 攻略第004讲
- [黑金原创教程] FPGA那些事儿《设计篇 I》- 图像处理前夕
- c++ 的vector
- [OpenStack]Server status values
- iframe中使用jquery进行查找的方法【案例分析】
- 如何在开发项目里进行自我激励
- nginx反向代理及负载均衡(服务器负载,以后看)
- DHTML-----表格的创建和样式
- C#开发微信门户及应用(42)--使用Autofac实现微信接口处理的控制反转处理
- Webx之表单验证
- Android 项目的代码混淆,Android proguard 使用说明