1099 及set 的使用

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值