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

来源:牛课题霸第127题

难度:中等

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

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

输出:2345

求解思路:使用动态数组进行求解,如果str1.charAt(i)==str2.charAt(j)表示[i][j]这个位置可以形成子串dp[i][j]=dp[i-1][j-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);

相关推荐
NE_STOP8 小时前
MyBatis-配置文件解读及MyBatis为何不用编写Mapper接口的实现类
java
后端AI实验室13 小时前
用AI写代码,我差点把漏洞发上线:血泪总结的10个教训
java·ai
CoovallyAIHub13 小时前
Moonshine:比 Whisper 快 100 倍的端侧语音识别神器,Star 6.6K!
深度学习·算法·计算机视觉
CoovallyAIHub14 小时前
速度暴涨10倍、成本暴降6倍!Mercury 2用扩散取代自回归,重新定义LLM推理速度
深度学习·算法·计算机视觉
CoovallyAIHub14 小时前
实时视觉AI智能体框架来了!Vision Agents 狂揽7K Star,延迟低至30ms,YOLO+Gemini实时联动!
算法·架构·github
CoovallyAIHub14 小时前
开源:YOLO最强对手?D-FINE目标检测与实例分割框架深度解析
人工智能·算法·github
程序员清风14 小时前
小红书二面:Spring Boot的单例模式是如何实现的?
java·后端·面试
belhomme15 小时前
(面试题)Redis实现 IP 维度滑动窗口限流实践
java·面试
CoovallyAIHub15 小时前
OpenClaw:从“19万星标”到“行业封杀”,这只“赛博龙虾”究竟触动了谁的神经?
算法·架构·github