LCS.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * 相似度算法
  4. *
  5. * $lcs = new LCS();
  6. * 返回最长公共子序列
  7. * echo $lcs->getLCS("吉林宝源丰禽业公司","吉林业公司");
  8. * echo "<br/>";
  9. * //返回相似度
  10. * echo $lcs->getSimilar("吉林宝源丰禽业公司","吉林业公司");
  11. */
  12. namespace Qii\Library;
  13. class LCS
  14. {
  15. var $str1;
  16. var $str2;
  17. var $c = array();
  18. /*
  19. 返回串一和串二的最长公共子序列
  20. */
  21. public function getLCS($str1, $str2, $len1 = 0, $len2 = 0) {
  22. $this->str1 = $str1;
  23. $this->str2 = $str2;
  24. if ($len1 == 0) $len1 = strlen($str1);
  25. if ($len2 == 0) $len2 = strlen($str2);
  26. $this->initC($len1, $len2);
  27. return $this->printLCS($this->c, $len1 - 1, $len2 - 1);
  28. }
  29. /*
  30. 返回两个串的相似度
  31. */
  32. public function getSimilar($str1, $str2) {
  33. $len1 = strlen($str1);
  34. $len2 = strlen($str2);
  35. $len = strlen($this->getLCS($str1, $str2, $len1, $len2));
  36. return $len * 2 / ($len1 + $len2);
  37. }
  38. /**
  39. * 将内容转成字符串
  40. *
  41. * @param int $len1 长度1
  42. * @param int $len2 长度2
  43. */
  44. protected function initC($len1, $len2) {
  45. for ($i = 0; $i < $len1; $i++) $this->c[$i][0] = 0;
  46. for ($j = 0; $j < $len2; $j++) $this->c[0][$j] = 0;
  47. for ($i = 1; $i < $len1; $i++) {
  48. for ($j = 1; $j < $len2; $j++) {
  49. if ($this->str1[$i] == $this->str2[$j]) {
  50. $this->c[$i][$j] = $this->c[$i - 1][$j - 1] + 1;
  51. } else if ($this->c[$i - 1][$j] >= $this->c[$i][$j - 1]) {
  52. $this->c[$i][$j] = $this->c[$i - 1][$j];
  53. } else {
  54. $this->c[$i][$j] = $this->c[$i][$j - 1];
  55. }
  56. }
  57. }
  58. }
  59. /**
  60. * 返回子串是否一致
  61. *
  62. * @param $c
  63. * @param $i
  64. * @param $j
  65. * @return string
  66. */
  67. protected function printLCS($c, $i, $j) {
  68. if ($i == 0 || $j == 0) {
  69. if ($this->str1[$i] == $this->str2[$j]) return $this->str2[$j];
  70. else return "";
  71. }
  72. if ($this->str1[$i] == $this->str2[$j]) {
  73. return $this->printLCS($this->c, $i - 1, $j - 1).$this->str2[$j];
  74. } else if ($this->c[$i - 1][$j] >= $this->c[$i][$j - 1]) {
  75. return $this->printLCS($this->c, $i - 1, $j);
  76. } else {
  77. return $this->printLCS($this->c, $i, $j - 1);
  78. }
  79. }
  80. }