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);

相关推荐
jonyleek1 分钟前
开源APS排产系统,出货计划如何成为企业降本增效的关键?
算法·开源·私有化部署·软件开发·生产排产·aps排产系统
hetao17338372 分钟前
2026-01-16~19 hetao1733837 的刷题笔记
c++·笔记·算法
LiRuiJie5 分钟前
从OS层面深入剖析JVM如何实现多线程与同步互斥
java·jvm·os·底层
m0_719084115 分钟前
滴滴滴滴滴
java·开发语言
程序员-King.5 分钟前
day153—回溯—子集(LeetCode-78)
算法·leetcode·回溯·递归
MicroTech202511 分钟前
突破C2Q瓶颈,MLGO微算法科技高性能可重构计算机实现量子算法真实级仿真,推动量子仿真进入新阶段
科技·算法·重构
张乔2417 分钟前
spring boot项目中设置默认的方法实现
java·数据库·spring boot
heartbeat..20 分钟前
数据库性能优化:SQL 语句的优化(原理+解析+面试)
java·数据库·sql·性能优化
Qhumaing27 分钟前
Java学习——第五章 异常处理与输入输出流笔记
java·笔记·学习
阿杰 AJie30 分钟前
MyBatis-Plus 比较运算符
java·数据库·mybatis