Description
给定 n 个字符串,求有多少字符串是其他字符串的前缀。Input
第一行为一个整数n(1 <= n <= 1000),之后n行,每行一个字符串,字符串只由26个小写字母组成,最大长度为100。Output
一个整数,有多少字符串是其他字符串的前缀。Sample Input
5 abcde ab bcde b cdeSample Output
2
#include <set> #include <algorithm> #include <string> using namespace std; int main() { set<string> s; set<string> p; set<string> chong; string a[2000] ; int sum = 0; int n; cin>>n; for(int i = 0;i < n;i ++)/ { cin>>a[i]; if(p.count(a[i])) chong.insert(a[i]); p.insert(a[i]); for(int j = 1;j < a[i].length();j++) { string str = a[i].substr(0,j); s.insert(str);} } for(int i = 0;i < n;i ++) { if(chong.count(a[i])) sum ++; else if(s.count(a[i])) sum ++; else continue; } cout<<sum<<endl; return 0; }
本体思路:先考虑特殊情况,自身是自身的前缀。所以利用p数组把a[2000] 中的重复数组存到chong
因为set具有唯一性
本题利用了枚举思想,把所有字符串的前缀存入到一个数组s里面
set中的count函数可以检测是否存在,所以利用set作为容器存储前缀
用一次循环把a中的元素挨个和s比较看是否相同。
注:两种情况,自身为前缀,真前缀
sdnu 1099
最新推荐文章于 2021-11-09 16:50:07 发布