KMP: Find a string that is both the prefix of the S1 string and the suffix of S2, and requires the maximum length of this string. The idea is to regard the S2 string as a text string, the S1 string as a mode string, and the two strings as KMP. For details, seeCode. Haha.
AC code:
View code
# Include <algorithm> # Include <Iostream> # Include <Cstdlib> # Include <Cstring> # Include <Cstdio> Using Namespace STD; Const Int Maxn =50000 + 5 ; Char S1 [maxn], S2 [maxn]; Int N, len1, len2, ANS, next [maxn]; Void Get_next (){ Int I = 0 , J =- 1 ; Next [ 0 ] =- 1 ; While (I < Len1 ){ If (J =- 1 | S1 [I] = S1 [J]) {I ++ ; J ++ ; If (S1 [I]! = S1 [J]) next [I] = J; Else Next [I] = Next [J];} Else J = Next [J] ;}} Void KMP (){ Int I = 0 , J = 0 ; While (I < Len2 ){ If (J =- 1 | S2 [I] = S1 [J]) I ++, J ++; Else J = Next [J];} If (J = 0 ) Printf ( " % D \ n " , 0 ); Else { For ( Int I =0 ; I <j; I ++ ) Printf ( " % C " , S1 [I]); printf ( " % D \ n " , J );}} Int Main (){ While (~ Scanf ( " % S % s " , S1, S2) {len1 = Strlen (S1); len2 = Strlen (S2); get_next (); KMP (); memset (S1, 0 , Sizeof (S1); memset (S2, 0 , Sizeof (S2 ));} Return 0 ;}
Now I understand how the experts are made. It is the best way to test your knowledge and increase your understanding. We also welcome criticism and correction.