题目要求:
描述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 ≤ 10, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 ≤ n ≤ 100000. 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
思路:先建树,然后对每个字符串进行查找,找到第一个时或全部查找完毕,退出。
#include<iostream>
#include<string>
using namespace std;
class tireNode {
public:
tireNode() {}
string text;
tireNode *next[10];
tireNode(string t)
{
text = t;
for (int i = 0;i < 10;i++)
{
next[i] = NULL;
}
}
};
tireNode * tireBuild(string *a,int nums)
{
tireNode *T=new tireNode("");
tireNode *current=T;
for (int i = 0;i < nums;i++)
{
current = T;
for (int j = 0;j < a[i].size();j++)
{
if (current->next[a[i][j]-'0'] == NULL)
{
string tmp = current->text;
tmp = tmp + a[i][j];
current->next[a[i][j] - '0'] = new tireNode(tmp);
current = current->next[a[i][j] - '0'];
}
else
{
current = current->next[a[i][j] - '0'];
}
}
}
return T;
}
bool search(tireNode *T,string *a,int nums)
{
tireNode *current;
for (int i = 0;i < nums;i++)
{
current = T;
for (int j = 0;j < a[i].size();j++)
{
if (current->next[a[i][j] - '0'] != NULL)
current = current->next[a[i][j] - '0'];
}
for (int j = 0;j < 10;j++)
{
if (current->next[j] != NULL)
{
return true;
}
}
}
return false;
}
int main()
{
int test_num;
//cout << "请输入测试用例的个数:" << endl;
cin >> test_num;
bool *res=new bool[test_num];
for (int i = 0;i < test_num;i++)
{
int nums;
//cout << "请输入用例"<<i+1<<"的行数:" << endl;
cin >> nums;
string *a = new string[nums];
tireNode *T;
bool condition;
for (int i = 0;i<nums;i++)
cin >> a[i];
T = tireBuild(a, nums);
condition = search(T, a, nums);
res[i] = condition;
}
for (int i = 0;i < test_num;i++)
{
if (res[i] == true)
{
//cout << "用例"<<i+1<<": "<<"存在某一个数是另外一个数的前缀!" << endl;
cout << "NO"<<endl;
}
else
{
//cout << "用例" << i + 1 << ": " "没有任何一个数是另外一个数的前缀!" << endl;
cout << "YES"<<endl;
}
}
system("pause");
}
tire tree的相关知识:(From: http://www.cnblogs.com/end/archive/2013/01/21/2870161.html)
一.Trie原理
Trie的核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。
二. Trie性质
1. 字符的种数决定每个节点的出度,即branch数组(空间换时间思想)。
2. branch数组的下标代表字符相对于a的相对位置
3. 采用标记的方法确定是否为字符串。
4. 插入、查找的复杂度均为O(len),len为字符串长度。