java求解最长公共字串

这篇博客介绍了如何使用Java实现动态规划算法来求解最长公共子串问题,内容包括对算法思想的引用及对最长公共子串与最长公共子序列区别的解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,很感谢仲达兄提供的算法思想,我是用了他的思想,才写出了这个用java求解的动态规划思想求解最长公共字串

仲达兄的博客地址是:http://blog.youkuaiyun.com/liufeng_king/article/details/8528858

再次感谢。

最长公共子串跟最长公共子序列是不一样的。最长字串要求要连接在一起,二子序列是不用的

public class LCSStrFromWen {
public static void main(String[] args) {
String S="hellotcl";
String T="tclhel";
System.out.println(getLCS(S,T));



public static String getLCS(String S, String T) {
>//第一步:创建一个二维的字符串数组,用来保存比较S T两个字符串中每一个char的结果
<span style="white-space:pre">	</span>String[][] temp = new String[T.length()][S.length(	</span>char charS;
	char charT;
	int S_len = S.length();int T_len = T.length();
		<int max_len = 0;//这个变量用来存储当前最大字串的长度
<span style="white-space:pre">	</span>for (int i = 0; i < T_len; i++) {//用T串去比较S串中的每一个字符
<span style="white-space:pre">		</span>for (int j = 0; j < S_len; j++)
<span style="white-space:pre">		</span>charT = T.charAt(i);//暂存要比较的字符
<span style="white-space:pre">		</span>charS = S.charAt(j);//同上
<span style="white-space:pre">		</span>if (charT != charS) {//不相等的时候,就在上面的数组中存入空字符串
<span style="white-space:pre">		</span>temp[i][j] = " ";
<span style="white-space:pre">		</span>} else {
<span style="white-space:pre">			</span>if (i == 0 || j == 0) {
<span style="white-space:pre">				</span>temp[i][j] = String.valueOf(charS);//相等的时候,要判断当前的位置
<span style="white-space:pre">			</span>} else {
<span style="white-space:pre">				</span>//动态规划的最重要的思想,如果当前不是i=0,j=0的状态时,存入的是斜对角的+当前的
<span style="white-space:pre">				</span>temp[i][j] = temp[i - 1][j - 1] + String.valueOf(charS);
<span style="white-space:pre">				</span>}
<span style="white-space:pre">			</span>if (temp[i][j].length() > max_len) {//判断当前的最长字符串
<span style="white-space:pre">				</span>max_len = temp[i][j].length();
<span style="white-space:pre">				</span>LCS = temp[i][j];
<span style="white-space:pre">				</span>}else if(temp[i][j].length() == max_len){
<span style="white-space:pre">					</span>LCS=LCS+","+temp[i][j];//如果有多个最长字符串,合并在一起输出
<span style="white-space:pre">				</span>}
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>return LCS;
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值