字典树:
1、基本概念
字典树,又称为单词查找树,Tire数,是一种树形结构,它是一种哈希树的变种。
2、基本性质
根节点不包含字符,除根节点外的每一个子节点都包含一个字符
从根节点到某一节点。路径上经过的字符连接起来,就是该节点对应的字符串
每个节点的所有子节点包含的字符都不相同
3、应用场景
典型应用是用于统计,排序和保存大量的字符串(不仅限于字符串),经常被搜索引擎系统用于文本词频统计。
4、优点
利用字符串的公共前缀来减少查询时间,最大限度的减少无谓的字符串比较,查询效率比哈希树高。
本题结题思路,用火星文构建一颗字典树,并将英文单词存在最后一个叶节点上,以from fiwo为例如下图所示,根节点是不存值的,目的是方便操作。
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
typedef struct Node
{
string ch;
Node *child[26];
Node() //用于初始化
{
ch = "";
memset(child, 0, sizeof(child)); //将所有孩子结点都初始化为0
}
};
Node *root = new Node; //必须用new,用malloc创建对象时不会调用构造函数初始化。
//new与malloc的区别,https://www.cnblogs.com/ywliao/articles/8116622.html
void Insert(string str1, string str2)
{
Node *p = root;
int len = str2.length();
for(int i = 0; i < len; i++)
{
int id = str2[i] - 'a';
if(p->child[id] == 0)
p->child[id] = new Node;
p = p->child[id];
}
p->ch = str1; //将单词插入到叶子结点
}
void search(string str, int len)
{
Node *p = root;
int i;
for(i = 0; i < len; i++)
{
int id = str[i] - 'a';
if(p->child[id] == 0)
break;
p = p->child[id];
}
//必须要判断p-ch是否为空,因为如果输入了火星文的单词的一部分,此时
//p->ch为空,所以应输出str而不是p->ch
if(i == len && p->ch != "")
cout << p->ch; //在字典树中找到了
else
cout << str; //在字典树中没有找到
}
int main()
{
string a, b, str;
cin >> a;
while(cin >> a && a != "END")
{
cin >> b;
Insert(a, b);
}
cin >> a;
getchar(); //下面的getline函数会接收空白字符,因此要用getchar把输入START后的回车吃掉
while(getline(cin, str) && str != "END")
{
string tmp;
for(int i = 0; i < str.length(); i++)
{
if(str[i] >= 'a' && str[i] <= 'z')
tmp += str[i];
else
{
search(tmp, tmp.length());
cout << str[i];
tmp = "";
}
}
if(tmp != "") //若输入的句子只有一个单词,那么再跳出for循环后还有search
search(tmp, tmp.length());
cout << endl;
}
return 0;
}