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

题目描写叙述:

给定两个字符串,求它们前后重叠的最长子串的长度,比方"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;
}


版权声明:本文博客原创文章。博客,未经同意,不得转载。

posted @ 2015-08-14 21:46  mengfanrong  阅读(231)  评论(0编辑  收藏  举报