PHP - 搜索回文时的效率

时间:2011-03-30 01:13:57

标签: php performance

我受到了一位朋友的挑战,想要编写一些PHP以找到所提供文本中最长的回文,我的解决方案如下,我怎样才能提高效率呢?

$string = file_get_contents("http://challenge.greplin.com/static/gettysburg.txt");

echo $string;

function isPalendrone($string) {
  if ($string == strrev($string))
    return true;
  else
    return false;
}

$longest = "";

for($i = 0; $i < strlen($string)-1; $i++) {
  $afterCurrent = substr($string, $i);
  for($j = 0; $j < strlen($afterCurrent)-1; $j++) {
    $section = substr($afterCurrent, 0, $j);
    if(isPalendrone($section)) {
      if(strlen($longest)<strlen($section)) {
        $longest = $section;
      }
    }
  }

}

echo "<br /><br/>The longest was: ".$longest."<br /> which is ".strlen($longest)." chars long";

2 个答案:

答案 0 :(得分:2)

这会反转整个字符串,只会substr()匹配每个字符串:

$rev = strrev($txt);
$len = strlen($txt);
$longest_len = 0;
$longest_str = null;

for ($i = 0; $i < $len; ++$i)
{
  for ($j = $len - $i; $j > $longest_len; --$j)
  {
    if (substr($txt, $i, $j) == substr($rev, $len-$i-$j, $j))
    {
      $longest_len = $j;
      $longest_str = substr($txt, $i, $j);
      break;
    }  
  }
}

我没有尝试优化实施。例如,跳过substr并执行char-by-char方法可能会快一些,因为你可以更快地爆发。在这种情况下,你甚至不需要反转字符串。

答案 1 :(得分:1)

要获得最长回文 - 你必须从最长的字符串开始(不像你现在那样做得最短),检查它并在第一场比赛中休息。

另外,您最好只保留2个指针($i$j),而不是执行substr两次。在您执行substr条件之前,只需要i和j以及if(isPalendrone())一次。

我的实施(比你的快〜20%):

<?php

$string = 'FourscoreandsevenyearsagoourfaathersbroughtforthonthiscontainentanewnationconceivedinzLibertyanddedicatedtothepropositionthatallmenarecreatedequalNowweareengagedinagreahtcivilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth';

function isPalendrone($string) {
  return $string == strrev($string);
}

$longest = '';
$length = strlen($string);

for ($i = 0; $i < $length - 1; $i++) {
    for ($j = $length - $i; $j > 1; $j--) {
        if (isPalendrone(substr($string, $i, $j))) {
            $new = substr($string, $i, $j);
            if (strlen($new) > strlen($longest)) $longest = $new;
            break;
        }
    }
}

echo "<br /><br/>The longest was: ".$longest."<br /> which is ".strlen($longest)." chars long";