码迷,mamicode.com
首页 > 其他好文 > 详细

B - Phone List

时间:2014-08-08 12:49:16      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:字符串前缀

Description

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:
1. Emergency 911
2. Alice 97 625 999
3. 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.
 

Input

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.
 

Output

For each test case, output “YES” if the list is consistent, or “NO” otherwise.
 

Sample Input

2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
 

Sample Output

NO YES

题目大意:

        给出几组字符串,判断每组字符串中是否存在某一个字符串是另外一个字符串的前缀的情况,如果有,就输出NO;如果没有,就输出YES。

输入:第一行一个整数t(1<=t<=40),表示有多少组测试数据;接下来的t组数据中,每组数据的第一行是一个整数n(1<=n<=10000),表示该组的数据个数,接着n行每行一个字符串。

解题思路:

       本题可以用字典树求解,但是我采用的是简单的查找。对每组数据,先按字典序对所以字符串排序,然后只需对比每两个相邻的字符串,判断它们是不是存在前缀关系即可。

代码如下:C/C++代码

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string>
using namespace std;
string s[10005];
//判断排序后的相邻的两个字符串是否是一个字符串是是另一个字符串的前缀
bool judge(int n)
{
    int i,j,m;
    for(i=0;i<n-1;i++)
    {
        m=s[i].size();
        for(j=0;j<m;j++)
        {
            if(s[i][j]!=s[i+1][j])
                break;
        }
        if(j==m)
            return false;
    }
    return true;
}
int main()
{
    int t,n,i;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(i=0;i<n;i++)
            cin>>s[i];//只能用cin输入,而不能用scanf输入
            //scanf("%s",&s[i]);
        sort(s,s+n);//按字典序排序
        if(judge(n))
           printf("YES\n");
        else
           printf("NO\n");
    }
    return 0;
}






B - Phone List,布布扣,bubuko.com

B - Phone List

标签:字符串前缀

原文地址:http://blog.csdn.net/yanghuaqings/article/details/38435675

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!