hdu 2594 Simpsons’ Hidden Talents KMP算法

来源:互联网 发布:合肥美工 编辑:程序博客网 时间:2024/05/17 06:09

题意:给两个字符串str1和str2, 求出是str1的前缀且是str2的后缀的最长的字符串(多组数据,而且长度可以到50000,千万不要有暴力的想法)

分析:把两个串连接起来得str3,求str3的next,若next[len3]不为零则有这样的串,把str1串前next[len3]个字符输出即可,为零则不存在。

需要一个特殊处理next[len3]大于给定两个串的最大一个时,取最小一个输出(比如 aaaaaa和aaa,只能输出3,你总不能输出大于3的数了吧)
代码:
<pre name="code" class="plain">var  s,x:ansistring;  len,w:longint;  next:array[0..100000] of longint;procedure get;var  i,j:longint;begin  next[0]:=-1;  next[1]:=0;  i:=2;  j:=0;  while i<=len do    if (j=-1)or(s[j+1]=s[i])      then begin             inc(j);             next[i]:=j;             inc(i);           end      else j:=next[j];end;begin  while not eof do  begin    readln(s);    w:=length(s);    readln(x);    if length(x)<w then w:=length(x);    s:=s+x;    len:=length(s);    get;    if next[len]>w then next[len]:=w;    if next[len]>0 then write(copy(s,1,next[len]),' ');    writeln(next[len]);  end;end.


0 0
原创粉丝点击