這篇文章主要介紹了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實現求解最長公用子串思路方法