九度1535 重叠的最长字串 字符串哈希

本文介绍了一种求解两字符串前后重叠最长子串的方法,通过哈希算法实现高效匹配,适用于字符串长度可达百万级别的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

给定两个字符串,求它们前后重叠的最长子串的长度,比如"abcde"和“cdefg”是"cde",长度为3。

输入:

输入可能包含多个测试案例。
对于每个测试案例只有一行, 包含两个字符串。字符串长度不超过1000000,仅包含字符'a'-'z'。

输出:

对应每个测试案例,输出它们前后重叠的最长子串的长度。

样例输入:
abcde cdefg
样例输出:
3

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <string.h>
#include <stdio.h>
using namespace std;
int maxLen(const char* S, const char* T) {
  int Slen = strlen(S), Tlen = strlen(T), i, j, minLen = min(Slen, Tlen), res = 0;
  typedef unsigned long long ull;
  ull Shash = 0, Thash = 0, t = 1, radix = 100000007;
  
  for (int i = 1; i <= minLen; ++i) {
    Shash = Shash + (S[Slen-i] - 'a') * t;
    Thash = Thash * radix + (T[i-1] - 'a');    
    t *= radix;
    if (Shash == Thash)
      res = i;
  }
  return res;
}
char a[1000000], b[1000000];

int main() {  
  while (scanf("%s%s",a,b) != EOF) {
    printf("%d\n",maxLen(a,b));
  }
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值