###求两个字符串的最长公共子串
算法思路:
1、把两个字符串分别以行和列组成一个二维矩阵。
2、比较二维矩阵中每个点对应行列字符中否相等,相等的话值设置为1,否则设置为0。
3、通过查找出值为1的最长对角线就能找到最长公共子串。
针对于上面的两个字符串我们可以得到的二维矩阵如下:
从上图可以看到,str1和str2共有5个公共子串,但最长的公共子串长度为5。
为了进一步优化算法的效率,我们可以再计算某个二维矩阵的值的时候顺便计算出来当前最长的公共子串的长度,即某个二维矩阵元素的值由record[i][j]=1演变为record[i][j]=1 +record[i-1][j-1],这样就避免了后续查找对角线长度的操作了。修改后的二维矩阵如下:
PHP代码实现如下:
$str1 = "abacdfgdcaba"; $str2 = "abacdgfdcaba"; $len1 = strlen($str1); $len2 = strlen($str2); $c = []; $maxLen = 0; $maxEnd = 0; for($i=0;$i<$len1;$i++){ for($j=0;$j<$len2;$j++){ if($str1[$i]==$str2[$j]){ if($i==0 || $j==0){ $c[$i][$j]=1; }else{ $c[$i][$j] = $c[$i-1][$j-1] + 1; } }else{ $c[$i][$j] = 0; } if($c[$i][$j]>$maxLen){ $maxLen = $c[$i][$j]; $maxEnd = $i; } } } echo $maxEnd." "; echo substr($str1,$maxEnd-$maxLen+1,$maxLen)
作者:南方以北
来源:CSDN
原文:https://blog.csdn.net/qq_25800311/article/details/81607168