PHP求解最長公用子串的方法

來源:互聯網
上載者:User
這篇文章主要介紹了PHP實現求解最長公用子串問題的方法,簡單描述了求解最長公用子串問題演算法原理,並結合執行個體形式分析了PHP實現求解最長公用子串的具體操作技巧,需要的朋友可以參考下

具體如下:

題目:如果字串一的所有字元按其在字串中的順序出現在另外一個字串二中,則字串一稱之為字串二的子串。

注意,並不要求子串(字串一)的字元必須連續出現在字串二中。即,可以不連續,但順序不能變。

請編寫一個函數,輸入兩個字串,求它們的最長公用子串,並列印出一個最長公用子串。

例如:輸入兩個字串BDCABA和ABCBDAB,字串BCBA和BDAB都是是它們的最長公用子串,

下面的演算法是根據網上的java演算法由酒逍遙 翻譯過來的

已經經過修正

LCS經典演算法php版本

<?phpclass LCS{  public static function main(){    //設定字串長度    $substringLength1 = 20;    $substringLength2 = 20; //具體大小可自行設定    $opt=array_fill(0,21,array_fill(0,21,null));    // 隨機產生字串    $x = self::GetRandomStrings($substringLength1);    $y = self::GetRandomStrings($substringLength2);    $startTime = microtime(true);    // 動態規劃計算所有子問題    for ($i = $substringLength1 - 1; $i >= 0; $i--){      for ($j = $substringLength2 - 1; $j >= 0; $j--){        if ($x[$i] == $y[$j])          $opt[$i][$j] = $opt[$i + 1][$j + 1] + 1;        else          $opt[$i][$j] = max($opt[$i + 1][$j], $opt[$i][$j + 1]);      }    }    echo "substring1:".$x."\r\n";    echo "substring2:".$y."\r\n";    echo "LCS:";    $i = 0;    $j = 0;    while ($i < $substringLength1 && $j < $substringLength2){      if ($x[$i] == $y[$j]){        echo $x[$i];        $i++;        $j++;      } else if ($opt[$i + 1][$j] >= $opt[$i][$j + 1])        $i++;      else        $j++;    }    $endTime = microtime(true);    echo "\r\n";    echo "Totle time is " . ($endTime - $startTime) . " s";  }  public static function GetRandomStrings($length){    $buffer = "abcdefghijklmnopqrstuvwxyz";    $str="";    for($i=0;$i<$length;$i++){      $random=rand(0,strlen($buffer)-1);      $str.=$buffer[$random];    }    return $str;  }}LCS::main();?>

運行結果:

substring1:cgqtdaacneftabsxvmlbsubstring2:suwjwwakzzhghbsmnksgLCS:absmTotle time is 0.000648975372314 s

相關推薦:

JavaScript求最大公用子串的方法詳解

詳解使用PHP求兩個字串最長公用子串

PHP實現求解最長公用子串思路方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.