Home > Backend Development > PHP Tutorial > PHP 最长公共子序列LCS 中文汉字版本怎么写?

PHP 最长公共子序列LCS 中文汉字版本怎么写?

WBOY
Release: 2016-06-06 20:42:06
Original
1576 people have browsed it

已经写了ASCII字母版

<code>function LCS($str_1, $str_2) {
  $len_1 = strlen($str_1);
  $len_2 = strlen($str_2);
  $len = $len_1 > $len_2 ? $len_1 : $len_2;

  $dp = array();
  for ($i = 0; $i  $dp[$i][$j - 1] ? $dp[$i - 1][$j] : $dp[$i][$j - 1];
      }
    }
  }

  return $dp[$len_1][$len_2];
}
</code>
Copy after login
Copy after login

如何扩展成中文版?

回复内容:

已经写了ASCII字母版

<code>function LCS($str_1, $str_2) {
  $len_1 = strlen($str_1);
  $len_2 = strlen($str_2);
  $len = $len_1 > $len_2 ? $len_1 : $len_2;

  $dp = array();
  for ($i = 0; $i  $dp[$i][$j - 1] ? $dp[$i - 1][$j] : $dp[$i][$j - 1];
      }
    }
  }

  return $dp[$len_1][$len_2];
}
</code>
Copy after login
Copy after login

如何扩展成中文版?

我自己解决了,只能自问自答了

<code><?php //最长公共子序列英文版
function LCS_en($str_1, $str_2) {
  $len_1 = strlen($str_1);
  $len_2 = strlen($str_2);
  $len = $len_1 > $len_2 ? $len_1 : $len_2;

  $dp = array();
  for ($i = 0; $i  $dp[$i][$j - 1] ? $dp[$i - 1][$j] : $dp[$i][$j - 1];
      }
    }
  }

  return $dp[$len_1][$len_2];
}

//拆分字符串
function mbStringToArray($string, $encoding = 'UTF-8') {
  $arrayResult = array();

  while ($iLen = mb_strlen($string, $encoding)) {
    array_push($arrayResult, mb_substr($string, 0, 1, $encoding));
    $string = mb_substr($string, 1, $iLen, $encoding);
  }

  return $arrayResult;
}

//最长公共子序列中文版
function LCS_cn($str1, $str2, $encoding = 'UTF-8') {
  $mb_len1 = mb_strlen($str1, $encoding);
  $mb_len2 = mb_strlen($str2, $encoding);

  $mb_str1 = mbStringToArray($str1, $encoding);
  $mb_str2 = mbStringToArray($str2, $encoding);

  $len = $mb_len1 > $mb_len2 ? $mb_len1 : $mb_len2;

  $dp = array();
  for ($i = 0; $i  $dp[$i][$j - 1] ? $dp[$i - 1][$j] : $dp[$i][$j - 1];
      }
    }
  }

  return $dp[$mb_len1][$mb_len2];
}
</code>
Copy after login
Related labels:
php
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