D2. Remove the Substring (hard version)(思维 )
2 seconds
256 megabytes
standard input
standard output
The only difference between easy and hard versions is the length of the string.
You are given a string ss and a string tt, both consisting only of lowercase Latin letters. It is guaranteed that tt can be obtained from ss by removing some (possibly, zero) number of characters (not necessary contiguous) from ss without changing order of remaining characters (in other words, it is guaranteed that tt is a subsequence of ss).
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 ss of maximum possible length such that after removing this substring tt will remain a subsequence of ss.
If you want to remove the substring s[l;r]s[l;r] then the string ss will be transformed to s1s2…sl−1sr+1sr+2…s|s|−1s|s|s1s2…sl−1sr+1sr+2…s|s|−1s|s| (where |s||s| is the length of ss).
Your task is to find the maximum possible length of the substring you can remove so that tt is still a subsequence of ss.
The first line of the input contains one string ss consisting of at least 11 and at most 2⋅1052⋅105 lowercase Latin letters.
The first line of the input contains one string tt consisting of at least 11 and at most 2⋅1052⋅105 lowercase Latin letters.
It is guaranteed that tt is a subsequence of ss.
Print one integer — the maximum possible length of the substring you can remove so that tt is still a subsequence of ss.
bbaba
bb
3
baaba
ab
2
abcde
abcde
0
asdfasdf
fasd
3
算法:思维
题解:匹配字串问题,我们可以先找到第一个子串出现的位置,记录到一个数组f里面,然后从后往前匹配,每次获取最大的长度,前面那个字符第一次出现的位置,如果a串中有一个字符和b串的字符相等,就向前推一个字符,继续寻找。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath> using namespace std; const int maxn = 2e5+; typedef long long ll; string a;
string b;
int f[maxn]; int main() {
cin >> a >> b;
f[] = -;
int k = ;
for(int i = , j = ; i < a.size(); i++) {
if(j < b.size() && a[i] == b[j]) { //找到第一个子串的位置
f[k++] = i;
j++;
}
}
int ans = ;
for(int i = a.size() - , j = ; i >= ; i--) {
ans = max(ans, i - f[b.size() - j]);
if(j < b.size() && a[i] == b[b.size() - j - ]) {
j++;
}
}
cout << ans << endl;
return ;
}
最新文章
- [译] 企业级 OpenStack 的六大需求(第 3 部分):弹性架构、全球交付
- HTML常用命名和CSS reset代码【收集总结】
- dom4j操作xml
- CSS长度单位
- 错误 1 无法嵌入互操作类型“Microsoft.Office.Interop.Excel.ApplicationClass”。请改用适用的接口
- sql连接查询 2011-10-10 23:13 (QQ空间)
- Android应用程序基础
- JavaWeb 后端 <;四>; 之 Cookie HttpSession 学习笔记
- AngularJS 和 Bootstrap
- css3文字与字体样式
- 【2017集美大学1412软工实践_助教博客】团队作业4——第一次项目冲刺(Alpha版本)小组 成绩
- Java I/O---字符与字节转换流---FileReader&;FileWriter:
- RabbitMQ之php-amqplib使用
- LIN 笔记
- 【Linux】Centos之安装Nginx及注意事项
- which/whereis/locate/find的区别
- Asterisk1.8 sip编码协商分析
- WITH HINDSIGHT
- tp between
- innodb 行级锁