Detailed explanation of using PHP to find the longest common substring of two strings

*文
Release: 2023-03-19 08:56:02
Original
2244 people have browsed it

How to find the longest common substring of two strings using PHP? This article mainly introduces the method of finding the longest common substring of two strings in PHP, involving the traversal, operation, judgment and other related operation skills of PHP strings and arrays. Friends in need can refer to it. I hope to be helpful.

The previous PHP method for solving the longest common substring problem is based on Java improvements. Here we look at another common substring algorithm.

The code is as follows:

<?php
$a = &#39;abceee12345309878&#39;;
$b = &#39;abceeew2345i09878fsfsfsfabceeewsfsdfsfsabceeew&#39;;
$c = array();
$lenht1 = strlen($a);
$lenth2 = strlen($b);
$startTime = microtime(true);
for ($i=0;$i<$lenht1;$i++) {
  for ($j=0;$j<$lenth2;$j++) {
    $n = ($i-1>=0 && $j-1>=0)?$c[$i-1][$j-1]:0;
    $n = ($a[$i] == $b[$j]) ? $n+1:0;
    $c[$i][$j] = $n;
  }
}
foreach ($c as $key=>$val) {
  $max = max($val);
  foreach ($val as $key1 =>$val1) {
    if ($val1 == $max && $max>0) {
      $cdStr[$max] = substr($b,$key1-$max+1,$max);
    }
  }
}
ksort($cdStr);
$endTime = microtime(true);
echo "Totle time is " . ($endTime - $startTime) . " s"."<br/>";
print_r(end($cdStr));
exit;
?>
Copy after login

Running results:

Totle time is 0.0012800693512 s
abceee
Copy after login

Related recommendations:

##Detailed explanation of PHP advanced Precision operation BC function library

Detailed explanation of the method of calculating the stability of student scores in PHP

PHP’s session deserialization vulnerability detailed explanation

The above is the detailed content of Detailed explanation of using PHP to find the longest common substring of two strings. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template