This article mainly introduces the method of solving the longest common substring problem in PHP, briefly describes the algorithm principle of solving the longest common substring problem, and analyzes the practical operation skill of PHP to solve the longest common substring with the example form, and needs friends to refer to
Specific as follows:
title: If all characters of string one appear in the order of the strings in the other string two, then the string is called a substring of string two.
Note that a character that does not require a substring (string one) must appear consecutively in string two. That is, it can be discontinuous, but the order cannot change.
Write a function, enter two strings, ask for their longest common substring, and print out one of the longest common substrings.
For example: Enter two strings Bdcaba and Abcbdab, string BCBA and Bdab are their longest common substrings,
The following algorithm is based on the Java algorithm on the Internet by the wine-carefree translation come over
has been amended
LCS Classic Algorithm PHP version
<?phpclass lcs{public static function main () {//Set string length $substringLength 1 = 20; $substringLength 2 = 20; The specific size can be set by itself $opt =array_fill (0,21,array_fill (0,21,null)); Randomly generated string $x = Self::getrandomstrings ($substringLength 1); $y = Self::getrandomstrings ($substringLength 2); $startTime = Microtime (true); Dynamic programming calculates all sub-problems for ($i = $substringLength 1-1; $i >= 0; $i-) {for ($j = $substringLength 2-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 < $substringLength 1 && $j < $substringLength 2) {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 ();? >
Operation Result:
Substring1:cgqtdaacneftabsxvmlbsubstring2:suwjwwakzzhghbsmnksgLCS:absmTotle Time is 0.000648975372314 s
Related recommendations:
JavaScript how to find the largest common substring
A detailed description of using PHP to find the longest common substring of two strings
PHP implementation of the longest common substring thinking method