8 动态规划解最长公共子串

来源:牛课题霸第127题

难度:中等

描述:给定两个字符串str1和str2,输出两个字符串的最长公共子串,题目保证str1和str2的最长公共子串存在且唯一。

示例1:"1AB2345CD","12345EF"

输出:2345

求解思路:使用动态数组进行求解,如果str1.charAt(i)==str2.charAt(j)表示ij这个位置可以形成子串dpij=dpi-1j-1+1,并与最大值进行比较并进行记录;否则为0,

java 复制代码
public String getMaxSubString(String str1,String str2)
{
int dp[][]=new int[str1.length()][str2.length()];
if(str1.charAt(0)==str2.charAt(1))
{
dp[0][0]=1;
}
else
{
dp[0][0]=0;
}
int maxLength=0;
int maxIndex=0;
for(int i=1;i<str1.length();i++)
{
for(int j=1;j<str2.length();j++)
{
if(str1.charAt(i)==str2.charSt(j))
{
dp[i][j]=dp[i-1][j-1]+1;
maxLength=Math.max(maxLength,dp[i][j]);
maxIndex=Math.max(maxIndex,i);
}else
{
dp[i][j]=0;
}
}
}
return str1.substring(maxIndex-maxLength+1,maxIndex+1);
}

String.substring的用法是String.subString(beginIndex,endIndex);取得是beginIndex-endIndex-1之间的子串,从而我们想取到maxIndex这个元素,需要return str1.substring(maxIndex-maxLength+1,maxIndex+1);

相关推荐
骄马之死4 小时前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端
Frostnova丶4 小时前
【算法笔记】数学知识
笔记·算法
吴可可1235 小时前
AutoCAD 2016与2014二次开发关键差异
算法
郑洁文5 小时前
基于Spring Boot的流浪动物救助网站
java·spring boot·后端·毕设·流浪动物救助
雨白6 小时前
哈希:以时间换空间的算法实战
算法
螺丝钉code6 小时前
JAVA项目 Claude code CLAUDE.md 到底应该怎么写
java·人工智能·claude code
摇滚侠7 小时前
Maven 入门+高深 单一架构案例 54-59
java·架构·maven·intellij-idea
VidDown7 小时前
Webhook 调试器:让第三方回调“原形毕露”
java·开发语言·javascript·编辑器·postman
San813_LDD7 小时前
[数据结构]LeetCode学习
数据结构·算法·图论