- 题意:给两个字符串,问相同子串的最大长度。
- 思路:首先最大长度肯定是在短的字符串长度(记为_min)之内的,这个不可置疑。所以我们对_min进行二分。至于那怎么更新二分区间呢?也就是judge函数怎么来写?我们将较长字符串的长度为mid的子串哈希值存起来,然后再遍历较短字符串长度为mid的子串哈希值【直接lower_bound即可】。【这里本来用的是set,但是T了(OS: 这才几天被卡了好几次set了www,其实也是我自己不是很会算时间复杂度qaq,都是觉得差不多就敲了www),于是开数组存,然后再排序了。】
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define INF 0x3f3f3f3f
#define lowbit(x) x & (-x)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxN = 100000 + 7;
const int base = 233;
ull Hash[2][maxN], p[maxN];
void pre()
{
p[0] = 1;
for(int i = 1; i <= 100000; i ++ )
p[i] = p[i - 1] * base;
}
ull get_hash(int l, int r, ull *g)
{
return g[r] - g[l - 1] * p[r - l + 1];
}
char str[2][maxN];
int len[2], _min, _max;
bool judge(int x)
{
ull cas[maxN]; int cnt = 0;
for(int i = 1; i <= len[_max] - x + 1; i ++ )//枚举左端点
cas[cnt ++ ] = get_hash(i, i + x - 1, Hash[_max]);
sort(cas, cas + cnt);
cnt = unique(cas, cas + cnt) - cas;//有没有都可
for(int i = 1; i <= len[_min] - x + 1; i ++ )
{
ull tar = get_hash(i, i + x - 1, Hash[_min]);
if(cas[lower_bound(cas, cas + cnt, tar) - cas] == tar)
return true;
}
return false;
}
int main()
{
pre();
while(~scanf("%s%s", str[0], str[1]))
{
len[0] = strlen(str[0]);
len[1] = strlen(str[1]);
Hash[0][0] = 0;
for(int i = 1; i <= len[0]; i ++ )
Hash[0][i] = Hash[0][i - 1] * base + str[0][i - 1] - 'a' + 1;
Hash[1][0] = 0;
for(int i = 1; i <= len[1]; i ++ )
Hash[1][i] = Hash[1][i - 1] * base + str[1][i - 1] - 'a' + 1;
if(len[0] <= len[1])
{
_min = 0;
_max = 1;
}
else
{
_min = 1;
_max = 0;
}
int l = 0, r = len[_min], mid;
int ans = 0;
while(r >= l)
{
mid = (l + r) >> 1;
if(judge(mid))//有,往大了找
{
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
printf("%d\n", ans);
}
return 0;
}