1. <?php
    2. class Solution {
    3. public $res = "";
    4. public $max = 0;
    5. // 中心扩散
    6. public function longestPalindrome($s) {
    7. $this->init();
    8. if (strlen($s) <= 1) return $s;
    9. for ($i = 0; $i < strlen($s); $i++) {
    10. $this->diffusion($s, $i, $i);
    11. $this->diffusion($s, $i, $i + 1);
    12. }
    13. return $this->res;
    14. }
    15. private function diffusion($s, $left, $right) {
    16. while($left >= 0 && $right < strlen($s) && $s[$left] == $s[$right]) {
    17. $newLen = $right - $left + 1;
    18. if ($newLen > $this->max) {
    19. $this->max = $newLen;
    20. $this->res = substr($s, $left, $newLen);
    21. }
    22. $left--;
    23. $right++;
    24. }
    25. }
    26. // 动态规划
    27. public function longestPalindrome2($s) {
    28. $this->init();
    29. if (strlen($s) <= 1) return $s;
    30. $this->res = $s[0];
    31. if ($s[0] == $s[1]) {
    32. $this->res = substr($s, 0, 1);
    33. }
    34. for ($j = 2; $j < strlen($s); $j++) {
    35. $dp[$j][$j] = true;
    36. for($i = 0; $i < $j; $i++) {
    37. $dp[$i][$j] = ($s[$i] == $s[$j]) && (($j - $i <= 2) || $dp[$i + 1][$j - 1]);
    38. if ($dp[$i][$j] && $this->max < $j - $i + 1) {
    39. $this->max = $j - $i + 1;
    40. $this->res = substr($s, $i, $j - $i + 1);
    41. }
    42. }
    43. }
    44. return $this->res;
    45. }
    46. private function init() {
    47. $this->res = '';
    48. $this->max = 0;
    49. }
    50. }
    51. $str = 'abbasabbbb';
    52. $cls = new Solution();
    53. $ret = $cls->longestPalindrome($str);
    54. print_r($ret);
    55. echo "\n";
    56. $ret2 = $cls->longestPalindrome2($str);
    57. print_r($ret2);