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
题意:
类似于在STL专题 中做过的题,即给你几组字符串,寻找里面是否有一组是另一组的 前缀,即给你几个字符串,让你寻找是否有包含的关系,即某一字符串是不是为另一字符串的子串。
思路:
对字符串进行排序,排序完之后,注意 此时可以find函数来寻找是否有包含关系,即v[i+1].find(v[i]);即在v[i+1]里面看能否找到v[i],如果找到则为0,输出“NO”,运用标识符,判断"YES"的情况。
代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<string>v;
string s;
int n,i,j,k;
while(cin>>n)
{
if(n==0)
break;
int flag=0;
v.clear();
for(i=0;i<n;i++)
{
cin>>s;
v.push_back(s);
}
sort(v.begin(),v.end());
for(j=0;j<n-1;j++)
{
if(v[j+1].find(v[j])==0)
{
flag++;
}
}
if(flag==0)
cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
细节:
注意STL的运用,采用find函数,省事省力!