D. Remove the Substring
Problem
You are given a string s s s and a string t t t, both consisting only of lowercase Latin letters. It is guaranteed that t t t can be obtained from s s s by removing some (possibly, zero) number of characters (not necessary contiguous) from s s s without changing order of remaining characters (in other words, it is guaranteed that t t t is a subsequence of s s 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 s s of maximum possible length such that after removing this substring t will remain a subsequence of s s s.
If you want to remove the substring s [ l ; r ] s[l;r] s[l;r] then the string s s s will be transformed to s 1    s 2    …    s l − 1    s r + 1    s r + 2    …    s ∣ s ∣ − 1    s ∣ s ∣ s_1 \; s_2 \; … \; s_{l−1} \; s_{r+1} \; s_{r+2} \; … \; s_{|s|−1} \; s_{|s|} s1s2…sl−1sr+1sr+2…s∣s∣−1s∣s∣ (where ∣ s ∣ |s| ∣s∣ is the length of s s s).
Your task is to find the maximum possible length of the substring you can remove so that t t t is still a subsequence of s s s.
Input
The first line of the input contains one string s s s consisting of at least 1 1 1 and at most 2 × 1 0 5 2 \times 10^5 2×105 lowercase Latin letters.
The second line of the input contains one string t t t consisting of at least 1 1 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
input
bbaba
bb
output
3
input
baaba
ab
output
2
input
abcde
abcde
output
0
input
asdfasdf
fasd
output
3
想法
题目大意是从S串中删除一些串使得剩下的串首尾相连构成T串,并且求最长的删除串的长度。题目保证T串可由S串任意删除字母而构成。
总的来说分三种情况
1.最长删除串在左端
2.最长删除穿在右端
3.最长删除串在中间
假设现在有S串和T串,那么为了使得删除串的长度最大,情况1就必须要使得第一个T串字母在S串的位置往后靠;情况2必须要往两端靠;情况3需要往前靠这样就可以使得删除串尽可能长
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
string s, t;
cin >> s >> t;
vector<int> rg(t.size());
for (int i = int(t.size()) - 1; i >= 0; --i) {
int pos = int(s.size()) - 1;
if (i + 1 < int(t.size())) pos = rg[i + 1] - 1;
while (s[pos] != t[i]) --pos;
rg[i] = pos;
}
int ans = 0;
int pos = 0;
for (int i = 0; i < int(s.size()); ++i) {
int rpos = int(s.size()) - 1;
if (pos < int(t.size())) rpos = rg[pos] - 1;
ans = max(ans, rpos - i + 1);
if (pos < int(t.size()) && t[pos] == s[i]) ++pos;
}
cout << ans << endl;
return 0;
}