首页 > php教程 > PHP源码 > 正文

用PHP求解最长公共子串问题

PHP中文网
发布: 2016-05-25 17:10:12
原创
1621人浏览过

php求解最长公共子串问题

<?php
class 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();
?>
登录后复制

                   

 以上就是用PHP求解最长公共子串问题的内容,更多相关内容请关注PHP中文网(www.php.cn)!

AI建筑知识问答
AI建筑知识问答

用人工智能ChatGPT帮你解答所有建筑问题

AI建筑知识问答 22
查看详情 AI建筑知识问答

相关标签:
php
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号