ACM题目————STL练习之求次数

本文探讨了解决字符串匹配问题的不同方法,包括使用 map、set 和结构化字符串排序等技术,提供了两种实现方式和一个优化解法。通过实例演示了如何在给定条件下计算特定字符串子串的重复次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:http://acm.nyist.net/JudgeOnline/problem.php?pid=1112

描述

题意很简单,给一个数n 以及一个字符串str,区间【i,i+n-1】 为一个新的字符串,i 属于【0,strlen(str)】如果新的字符串出现过ans++,例如:acmacm n=3,那么 子串为acm cma mac acm ,只有acm出现过

求ans;

输入
LINE 1: T组数据(T<10)
LINE 2: n ,n <= 10,且小于strlen(str);
LINE 3:str
str 仅包含英文小写字母 ,切长度小于10w
输出
求 ans
样例输入
2
2
aaaaaaa
3
acmacm
样例输出
5
1

map解法:

 

//Asimple

#include <iostream>
#include <map>
#include <cstdio>

using namespace std;
int T, n, ans;
string str;

int main()
{
    scanf("%d",&T);
//    cin >> T;//TLE了三次,没想到竟然是 cin 的错
    while( T-- )
    {
        cin >> n >> str ;
        ans = 0;
        map<string,int> m;
        int len = str.length();
        for(int i=0; i<=len-n; i++)
        {
            string s = str.substr(i,n);
            if( m[s] == 1 ) ans ++ ;
            else m[s] = 1 ;
        }
        cout << ans << endl ;
    }

    return 0;
}

 

set解法:

 

//Asimple

#include <iostream>
#include<cstdio>
#include<cstring>
#include <set>
using namespace std;

int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        int n,i, ans = 0;
        scanf("%d", &n);
        set<string> S;
        string str, s;
        cin >> str;
        int len = str.length();
        int lens=str.size();
        for(i=0; i<=len-n; i++)
        {
            s=str.substr(i,n);
            S.insert(s);
            if(S.size()==lens) ans++;
            else lens=S.size();
        }
        printf("%d\n", ans);
    }
    return 0;
}

 

最优解,结构字符串排序:

//Asimple
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

struct str
{
    char s[12];
} r[100001];

int n;
char _str[100001];

void _strcpy(int x, int y)
{
    int j;

    for (j=0; j<n; j++)
        r[x].s[j] = _str[y+j];
    r[x].s[j] = '\0';
    return ;
}

bool cmp(str a, str b)
{
    return strcmp(a.s, b.s) < 0;
}

int main()
{
    int T, i, count, l;
    scanf("%d", &T);
    while (T--)
    {
        count = 0;
        memset(_str, '\0', sizeof(_str));
        scanf("%d", &n);
        scanf("%s", _str);
        l = strlen(_str);
        for (i=0; i<=l-n; i++)
            _strcpy(i, i);
        sort(r, r+l-n+1, cmp);

        for (i=0; i<l-n; i++)
            if (strcmp(r[i].s, r[i+1].s) == 0)
                count++;
        printf("%d\n", count);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/Asimple/p/5505645.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值