题目链接:http://codeforces.com/contest/1492/problem/C
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: s of length n and t of length m.
A sequence p1,p2,…,pm, where 1≤p1<p2<…<pm≤n, is called beautiful, if spi=ti for all i from 1 to m. The width of a sequence is defined as max1≤i<m(pi+1−pi).
Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings s and t there is at least one beautiful sequence.
Input
The first input line contains two integers n and m (2≤m≤n≤2⋅105) — the lengths of the strings s and t.
The following line contains a single string s of length n, consisting of lowercase letters of the Latin alphabet.
The last line contains a single string t of length m, consisting of lowercase letters of the Latin alphabet.
It is guaranteed that there is at least one beautiful sequence for the given strings.
Output
Output one integer — the maximum width of a beautiful sequence.
Examples
input
5 3
abbbc
abc
output
3
input
5 2
aaaaa
aa
output
4
input
5 5
abcdf
abcdf
output
1
input
2 2
ab
ab
output
1
分析
只要找到 t 串中每个字符在 s 串可能的位置中最靠坐的和最靠右的,然后都进行比较即可得到答案。
代码
#include<bits/stdc++.h>
using namespace std;
#define lli long long int
lli forw[200007];
lli back[200007];
int main(){
lli n,m;
cin>>n>>m;
string s,t;
cin>>s>>t;
for(lli i=0,j=0;i<n && j<m;i++)
{
if(t[j]==s[i])
{
forw[j]=i;
j++;
}
}
for(lli i=n-1,j=m-1;i>0 && j>0;i--)
{
if(t[j]==s[i])
{
back[j]=i;
j--;
}
}
lli maxi=0;
for(int i=0;i<m-1;i++)
maxi=max(maxi,back[i+1]-forw[i]);
cout<<maxi;
return 0;
}