ZOJ-3643-Keep Deleting【字符串】


3643-Keep Deleting


                Time Limit:2000MS     Memory Limit:65536KB

Description
Assume that string A is the substring of string B if and only if we can find A in B, now we have a string A and another string B, your task is to find a A in B from B’s left side to B’s right side, and delete it from B till A is not a substring of B, then output the number of times you do the delete.

There are only letters(A-Z, a-z) in string A and B.

Input
This problem contains multiple test cases. Each case contains two line, the first line is string A, the second line is string B, the length of A is less than 256, the length of B is less than 512000.

Output
Print exactly one line with the number of times you do the delete for each test case.

Sample Input
abcd
abcabcddabcdababcdcd

Sample Output
5

题目链接:ZOJ-3643

题目大意:给出一个sub字串,s原串,每次操作从s中删去一个sub。一直删到没有为止。

eg:

abcabcddabcdababcdcd delete=0
abcdabcdababcdcd     delete=1
abcdababcdcd         delete=2
ababcdcd             delete=3
abcd                 delete=4
                     delete=5

题目思路: 设置一个数组pre,记录当前字母前一个字母的下标

初始:
这里写图片描述

删除一个abcd之后:

这里写图片描述

以下是代码:

#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
int pre[512005];
int main()
{
    string s,sub;
    while(cin >> sub >> s)
    {
        for (int i = 1; i < s.size(); i++)
        {
            pre[i] = i - 1;
        }
        char alp = sub[sub.size() - 1];
        int ans = 0;
        for (int i = sub.size() - 1; i < s.size(); i++)
        {
            if (s[i] == alp)  //遍历是否为终点
            {
                int flag = 0;
                int last = 0;
                for (int j = i,k = 0; k < sub.size() ; j = pre[j],k++)
                {
                    if (j < 0) 
                    {
                        flag = 1;
                        break;
                    }
                    if (s[j] != sub[sub.size() - k - 1])
                    {
                        flag = 1;
                    }
                    last = j;
                }
                if (!flag)
                {
                    pre[i + 1] = last - 1;
                    ans++;
                }
            }
        }
        cout << ans << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值