PHP implements a method for solving the longest public substring problem. php solves the longest substring problem.
This example describes how PHP can solve the longest common substring problem. We will share this with you for your reference. The details are as follows:
Question:If all the characters of string 1 appear in the second string in the order of the strings, then string 1 is called a substring of string 2.
Note that the character of a substring (string 1) must appear in string 2 consecutively. That is, it can be discontinuous, but the sequence cannot be changed.
Compile a function, enter two strings, calculate their longest public substrings, and print out a longest public substrings.
For example, input two strings: BDCABA and ABCBDAB. Both BCBA and BDAB are their longest common substrings,
The following algorithms are translated by Xiaoyao liquor Based on the java Algorithm on the Internet.
Corrected
Php version of LCS classic algorithm
<? Phpclass LCS {public static function main () {// set the string length $ substringLength1 = 20; $ substringlengh2 = 20; // you can set the specific size by yourself $ opt = array_fill, array_fill (, null); // randomly generate a string $ x = self: GetRandomStrings ($ substringLength1); $ y = self: GetRandomStrings ($ substringleningg22 ); $ startTime = microtime (true); // All subproblems with dynamic planning and Calculation for ($ I = $ substringLength1-1; $ I >=0; $ I --) {for ($ j = $ substringlength1-1; $ j> = 0; $ J --) {if ($ x [$ I] = $ y [$ j]) $ opt [$ I] [$ j] = $ opt [$ I + 1] [$ j + 1] + 1; else $ opt [$ I] [$ j] = max ($ opt [$ I + 1] [$ j], $ opt [$ I] [$ j + 1]) ;}} echo "substring1 :". $ x. "\ r \ n"; echo "substring2 :". $ y. "\ r \ n"; echo "LCS:"; $ I = 0; $ j = 0; while ($ I <$ substringLength1 & $ j <$ substringleng22) {if ($ x [$ I] = $ y [$ j]) {echo $ x [$ I]; $ I ++; $ j ++ ;} else if ($ opt [$ I + 1] [$ j] >=$ opt [$ I] [$ j + 1]) $ I ++; else $ j ++ ;} $ EndTime = microtime (true); echo "\ r \ n"; echo "Totle time is ". ($ endTime-$ startTime ). "s";} public static function GetRandomStrings ($ length) {$ buffer = "abcdefghijklmnopqrstuvwxyz"; $ str = ""; for ($ I = 0; $ I <$ length; $ I ++) {$ random = rand (0, strlen ($ buffer)-1); $ str. = $ buffer [$ random];} return $ str ;}} LCS: main ();?>
Running result:
substring1:cgqtdaacneftabsxvmlbsubstring2:suwjwwakzzhghbsmnksgLCS:absmTotle time is 0.000648975372314 s