You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s).
For example, the strings “test”, “tst”, “tt”, “et” and “” are subsequences of the string “test”. But the strings “tset”, “se”, “contest” are not subsequences of the string “test”.
You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s.
If you want to remove the substring s[l;r] then the string s will be transformed to s1s2…sl−1sr+1sr+2…s|s|−1s|s| (where |s| is the length of s).
Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s.
Input
The first line of the input contains one string s consisting of at least 1 and at most 2⋅105 lowercase Latin letters.
The second line of the input contains one string t consisting of at least 1 and at most 2⋅105 lowercase Latin letters.
It is guaranteed that t is a subsequence of s.
Output
Print one integer — the maximum possible length of the substring you can remove so that t is still a subsequence of s.
Examples
inputCopy
bbaba
bb
outputCopy
3
inputCopy
baaba
ab
outputCopy
2
inputCopy
abcde
abcde
outputCopy
0
inputCopy
asdfasdf
fasd
outputCopy
3
题意: 两个字符串s,t,t串是s串的子串,删除s串中的连续子串,使得t仍然是s串的子串,问删除连续子串的最大长度。
思路: 要删除最长的连续子串只有两种情况,要么在s串的首或尾,要么在s串的中间。枚举t串中每一个字符在s串中对应的未匹配的第一个位置和最后一个位置,那么首部的最大连续子串即第一个字符的第一个位置,尾部的是最后一个字符的最后一个位置。对于处于中间情况的字符串来说,第i字符的最后一个位置 - 第i-1字符的第一个位置取最大即可。
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 2e5+10;
int a[MAXN];
int b[MAXN];
int main()
{
string s,t;
cin>>s>>t;
int ls = s.size();
int lt = t.size();
for(int i = 0, j = 0; i < ls && j < lt; ++i)
if(s[i] == t[j])
a[j++] = i;
for(int i = ls - 1, j = lt - 1; i >= 0 && j >= 0; --i)
if(s[i] == t[j])
b[j--] = i;
int mx = 0;
mx = max(mx,b[0]);
mx = max(mx,ls - a[lt-1] - 1);
for(int i = 1; i < lt; i++)
mx = max(mx,b[i] - a[i-1] - 1);
cout<<mx<<endl;
return 0;
}