1. 程式人生 > >查詢子字串的個數(二分法查詢)

查詢子字串的個數(二分法查詢)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <cstdlib>
#define LL long long
using namespace std;
char str1[500020],str2[500020];
bool check(int n)
{
    int l1=strlen(str1);
    int l2=strlen(str2);
    int count=0,k=0;
    for(int i=0; i<l2; i++)
    {
        if(str1[k]==str2[i])
            count++;
        if(count==n)
        {
            count=0;
            k++;
        }
        if(k==l1)
            return true;
    }
    return false;
}
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        cin>>str1>>str2;
        int l1=strlen(str1);
        int l2=strlen(str2);
        int l=0,r=l2/l1;
        while(r>l)
        {
            int m=l+(r-l)/2;
            if(check(m))
            {
                l=m+1;
            }
            else
            {
                r=m;
            }
        }
        if(check(l))
        cout<<l<<endl;
        else if(!check(l)&&l>0)
        cout<<l-1<<endl;
        else
        cout<<"0"<<endl;
    }
    return 0;
}