1099.前缀判断
Description
给定 n 个字符串,求有多少字符串是其他字符串的前缀。
Input
第一行为一个整数n(1 <= n <= 1000),之后n行,每行一个字符串,字符串只由26个小写字母组成,最大长度为100。
Output
一个整数,有多少字符串是其他字符串的前缀。
Sample Input
5 abcde ab bcde b cde
Sample Output
2
要想获取是其它元素的前缀的元素,就可以先将各个元素的所有前缀拆分开,把它们放到一个容器中,而依据set没有重复元素的特性,我们选择set这个容器。
但有一点需要注意,如果两个元素相同,那么它们互为前缀。
代码如下
#include <iostream> #include<cstdio> #include<set> #include<algorithm> #include<cstring> using namespace std; int main() { int n, i, j, h; int s = 0; int u = 0; int t = 0; string a[1005]; int b[1005]; set<string>str; string part; scanf("%d", &n); for(i = 0; i < n; i++) { cin >> a[i]; b[i] = a[i].size(); for(j = 1; j <= b[i] -1; j++) { part = a[i].substr(0,j); //取出前缀 str.insert(string(part)); } } for(i = 0; i < n; i++) { if(str.count(a[i])) { t++; s++; } if(s == 0) //set中未找到匹配,则与数组中的元素相互匹配 { for(h = 0; h < n; h++) { if(a[i] == a[h]) u++; } if(u - 1 != 0) t++;//减去自己本身 u = 0; } s = 0; } cout<<t<<endl; return 0; }