Description
We know that if a phone number A is another phone number B’s prefix, B is not able to be called. For an example, A is 123 while B is 12345, after pressing 123, we call A, and not able to call B.
Given N phone numbers, your task is to find whether there exits two numbers A and B that A is B’s prefix.
Given N phone numbers, your task is to find whether there exits two numbers A and B that A is B’s prefix.
Input
The input consists of several test cases.
The first line of input in each test case contains one integer N (0<N<1001), represent the number of phone numbers.
The next line contains N integers, describing the phone numbers.
The last case is followed by a line containing one zero.
The first line of input in each test case contains one integer N (0<N<1001), represent the number of phone numbers.
The next line contains N integers, describing the phone numbers.
The last case is followed by a line containing one zero.
Output
For each test case, if there exits a phone number that cannot be called, print “NO”, otherwise print “YES” instead.
Sample Input
2 012 012345 2 12 012345 0
Sample Output
NO YES
解题思路:
利用字符串数组,对于每个字符串查找它能否成为其它字符串的前缀,
细节处理:
若a是b的前缀则b比a长,对b从前往后取与a等长的字符串与a进行比较,如果只有一个字符串直接输出YES
代码:
#include <iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
int n,i,j,lena,lenb;
string a[1009];
while(cin>>n)
{
if(n==0) break;
for(i=1;i<=n;i++)
cin>>a[i];
if(n==1) {cout<<"YES"<<endl; continue;}
int flag=0;
for(i=1;i<=n;i++)
{
lena=a[i].length();
for(j=1;j<=n;j++)
{
lenb=a[j].length();
if(lenb>=lena&&i!=j)
{
string t;
for(int r=0;r<lena;r++)
{t+=a[j][r];}
if(t==a[i])
{flag=1; break;}
}
}
}
if(flag) cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
return 0;
}