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

相关推荐
NFA晨曦3 分钟前
力扣刷题日常(7-8)
算法·leetcode·c#
77qqqiqi8 分钟前
解决Property ‘sqlSessionFactory‘ or ‘sqlSessionTemplate‘ are required报错问题
java·数据库·微服务·mybatis·mybatisplus
weisian15111 分钟前
Java WEB技术-序列化和反序列化认识(SpringBoot的Jackson序列化行为?如何打破序列化过程的驼峰规则?如何解决学序列化循环引用问题?)
java·spring boot
橘子编程24 分钟前
SpringMVC核心原理与实战指南
java·spring boot·spring·tomcat·mybatis
小指纹1 小时前
图论-最短路 Bellman-Ford算法
c++·算法·objective-c·图论
屁股割了还要学1 小时前
【数据结构入门】时间、空间复杂度的计算
c语言·开发语言·数据结构·c++·算法
踏上青云路1 小时前
C# 闭包
java·前端·c#
倒悬于世1 小时前
ThreadLocal详解
java·开发语言·jvm
myjs9991 小时前
数学=符号
java·前端·算法
程序猿小D2 小时前
Java项目:基于SSM框架实现的校园活动资讯网管理系统【ssm+B/S架构+源码+数据库+毕业论文+远程部署】
java·数据库·mysql·spring·毕业设计·ssm框架·校园活动