字典树

字典树

又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来节约存储空间,最大限度地减少无谓的字符串比较,查询效率比哈希表高。 


字典树与字典很相似,当你要查一个单词是不是在字典树中,首先看单词的第一个字母是不是在字典的第一层,如果不在,说明字典树里没有该单词,如果在就在该字母的孩子节点里找是不是有单词的第二个字母,没有说明没有该单词,有的话用同样的方法继续查找.字典树不仅可以用来储存字母,也可以储存数字等其它数据。


Trie的数据结构可以定义为:

#define MAX 26
typedef struct Trie   
{   
    Trie *next[MAX];   
    int v;   //根据需要变化
};   
 
Trie *root;

next是表示每层有多少种类的数,如果只是小写字母,则26即可,若改为大小写字母,则是52,若再加上数字,则是62了,这里根据题意来确定。
v可以表示一个字典树到此有多少相同前缀的数目,这里根据需要应当学会自由变化。

Trie的查找(最主要的操作):
(1) 每次从根结点开始一次搜索;
(2) 取得要查找关键词的第一个字母,并根据该字母选择对应的子树并转到该子树继续进行检索;   (3) 在相应的子树上,取得要查找关键词的第二个字母,并进一步选择对应的子树进行检索。   
(4) 迭代过程……   
(5) 在某个结点处,关键词的所有字母已被取出,则读取附在该结点上的信息,即完成查找。


这里给出生成字典树和查找的模版:
生成字典树:

void createTrie(char *str)
{
    int len = strlen(str);
    Trie *p = root, *q;
    for(int i=0; i<len; ++i)
    {
        int id = str[i]-'a';
        if(p->next[id] == NULL)
        {
            q = (Trie *)malloc(sizeof(Trie));
            q->v = 1;    //初始v==1
            for(int j=0; j<MAX; ++j)
                q->next[j] = NULL;
            p->next[id] = q;
            p = p->next[id];
        }
        else
        {
            p->next[id]->v++;
            p = p->next[id];
        }
    }
    p->v = -1;   //若为结尾,则将v改成-1表示
}
接下来是查找的过程了:

int findTrie(char *str)
{
    int len = strlen(str);
    Trie *p = root;
    for(int i=0; i<len; ++i)
    {
        int id = str[i]-'0';
        p = p->next[id];
        if(p == NULL)   //若为空集,表示不存以此为前缀的串
            return 0;
        if(p->v == -1)   //字符集中已有串是此串的前缀
            return -1;
    }
    return -1;   //此串是字符集中某串的前缀
}
//对于上述动态字典树,有时会超内存,比如 Phone List,这是就要记得释放空间了:

int dealTrie(Trie* T)
{
    int i;
    if(T==NULL)
        return 0;
    for(i=0;i<MAX;i++)
    {
        if(T->next[i]!=NULL)
            dealTrie(T->next[i]);
    }
    free(T);
    return 0;
}

Phone List
Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let's say the phone catalogue listed these numbers:

Emergency 911
Alice 97 625 999
Bob 91 12 54 26
In this case, it's not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob's phone number. So this list would not be consistent.

输入
The first line of input gives a single integer, 1 ≤ t ≤ 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 ≤ n ≤ 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.

输出
For each test case, output "YES" if the list is consistent, or "NO" otherwise.

样例输入
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346
样例输出
NO
YES

代码如下:

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner (System.in);
		int n = input.nextInt();
		for (int i = 0;i < n;i++) {
			int m = input.nextInt();
			Trie tree = new Trie ();
			for (int j = 0;j < m;j++) {
				char[]ch = input.next().toCharArray();
				tree.createTrie(ch);
			}
			tree.traverse(tree.root);
			if (tree.flag < m) {
				System.out.println("NO");
			}else {
				System.out.println("YES");
			}
			tree = null;
		}
	}
}




class Trie {
	Node root = null;
	int flag =0;
	public Trie () {
		root = new Node();
	}
	public void createTrie (char []array) {
		Node p = root;
		for (int i = 0;i < array.length;i++) {
			int value = array[i] - '0';
			if (p.next[value] == null) {
				p.next[value] = new Node ();
				p.next[value].v++;
				p = p.next[value];
			}else {
				p.next[value].v++;
				p = p.next[value];
			}
		}
	}
	
	
	private boolean isEmpty (Node node) {
		for (int i = 0;i < node.next.length;i++) {
			if (null != node.next[i]) {
				return false;
			}
		}
		return true;
	}
	public void traverse (Node node) {
		if (isEmpty(node)) {
			flag++;
			return;
		}
		for (int i = 0;i < node.next.length;i++) {
				if (node.next[i] != null) {
					traverse(node.next[i]);
				}
		}
	}
}
class Node {
	Node[]next = new Node[10];
	int v = 0;
}

最短前缀
描述
一个字符串的前缀是从该字符串的第一个字符起始的一个子串。例如 "carbon"的字串是: "c", "ca", "car", "carb", "carbo", 和 "carbon"。注意到这里我们不认为空串是字串, 但是每个非空串是它自身的字串. 我们现在希望能用前缀来缩略的表示单词。例如, "carbohydrate" 通常用"carb"来缩略表示. 现在给你一组单词, 要求你找到唯一标识每个单词的最短前缀
在下面的例子中,"carbohydrate" 能被缩略成"carboh", 但是不能被缩略成"carbo" (或其余更短的前缀) 因为已经有一个单词用"carbo"开始
一个精确匹配会覆盖一个前缀匹配,例如,前缀"car"精确匹配单词"car". 因此 "car" 是 "car"的缩略语是没有二义性的 , “car”不会被当成"carriage"或者任何在列表中以"car"开始的单词.
输入
输入包括至少2行,至多1000行. 每行包括一个以小写字母组成的单词,单词长度至少是1,至多是20.
输出
输出的行数与输入的行数相同。每行输出由相应行输入的单词开始,后面跟着一个空格接下来是相应单词的没有二义性的最短前缀标识符。
样例输入
carbohydrate
cart
carburetor
caramel
caribou
carbonic
cartilage
carbon
carriage
carton
car
carbonate
样例输出
carbohydrate carboh
cart cart
carburetor carbu
caramel cara
caribou cari
carbonic carboni
cartilage carti
carbon carbon
carriage carr
carton carto
car car
carbonate carbona

代码如下:

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	public static ArrayList<String> lists = new ArrayList<String>();
	public static node root = new node ();
	public static void main(String[] args) {
		Scanner input = new Scanner (System.in);
		while (input.hasNext()) {
			String content = input.next();
		

			lists.add (content);
			create (content.toCharArray());
		}
		for (int i = 0;i < lists.size();i++) {
			String key = lists.get(i);
			String value = find (key.toCharArray());
			System.out.println(key+" "+value);
		}
	}
	static class node {
	//26小写字母
	node []nexts = new node[26];
	//表示经过此节点字符的个数总和
	int v = 0;
	}
	//构建字典树
	public static void create (char[]character) {
		node p = root;
		for (int i = 0;i < character.length;i++) {
			int id = character[i] - 'a';
			if (p.nexts[id] == null) {
				p.nexts[id] = new node ();
				p.nexts[id].v++;
				p = p.nexts[id];
			}else {
				p.nexts[id].v++;
				p = p.nexts[id];
			}
		}
	}
	//在字典树中查找某个单词
	public static String find (char[]character) {
		node p = root;
		StringBuilder builder = new StringBuilder ();
		for (int i = 0;i < character.length;i++) {
			int id = character[i] - 'a';
			p = p.nexts[id];
			builder.append(character[i]);
			if (p.v == 1) {
				return builder.toString();
			}
		}
		return builder.toString();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值