当前位置:网站首页>每日一题系列:公共子串计算
每日一题系列:公共子串计算
2022-04-22 12:47:00 【高邮吴少】
链接:https://www.nowcoder.com/questionTerminal/98dc82c094e043ccb7e0570e5342dd1b
来源:牛客网
给定两个只包含小写字母的字符串,计算两个字符串的最大公共子串的长度。
注:子串的定义指一个字符串删掉其部分前缀和后缀(也可以不删)后形成的字符串。
数据范围:字符串长度:1≤s≤150
进阶:时间复杂度:O(n^3) ,空间复杂度:O(n)

解题思路:
对于动态规划来说,我们没办法一下子解决这个大问题,需要划分成小问题,我们先看每个字符串的子串之间最大公共子串的长度,然后用小问题的解推倒大问题
我们定义一个函数:
F(i,j)表示以第一个字符串第i个字符结尾和第二个字符串第j个字符结尾的最大公共子串的长度
举个例子:

F(1,1)表示:第一个字符串的以第1个字符a结尾的子串,第二个字符串的以第1个字符w结尾的子串,最大公共子串长度为0
同理得:
F(2,3): … s,… r,最大公共子串长度为0
F(4,7): …f,… f,最大公共子串长度肯定大于等于1了(f是相同的,f前面的也有可能相同)
推广开来:
如果第i个字符!=第j个字符
F(i,j)=0
第i个字符==第j个字符
F(i,j)=F(i-1,j-1)+1
比如F(1,4)=1 字符串a
F(2,5)=F(1,4)+1=2 字符串as
F(3,6)=F(2,5)+1=3 字符串asd
初始状态:F(i,0)=F(0,j)=0
(你拿一个字符串和一个空串比,它们的子串肯定是0)
返回值:max(F(i,j))
代码如下:
import java.util.*;
public class Main{
public static int getMaxLen(String str1,String str2){
char[] arr1=str1.toCharArray();
char[] arr2=str2.toCharArray();
int l1=arr1.length;
int l2=arr2.length;
int[][] maxSubLen=new int[l1+1][l2+1];
int maxLen=0;
for(int i=1;i<=l1;i++){
for(int j=1;j<=l2;j++){
if(arr1[i-1]==arr2[j-1]){
//F(i,j)=F(i-1,j-1)+1
maxSubLen[i][j]=maxSubLen[i-1][j-1]+1;
//是否需要更新最大值
if(maxLen<maxSubLen[i][j]){
maxLen=maxSubLen[i][j];
}
}//如果不等,你就不用管了,原先数组里面默认就是0
}
}
return maxLen;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String str1=scanner.nextLine();
String str2=scanner.nextLine();
int x=getMaxLen(str1,str2);
System.out.println(x);
}
}
版权声明
本文为[高邮吴少]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_57180439/article/details/124329511
边栏推荐
- 给自己成功的可能性
- [concurrent programming 053] Why use volatile variables for double check lock variables
- JS盒子点击时跟随鼠标移动
- ES6解构赋值之数组的解构赋值
- matlab 土力学混凝土桩号 受力计算程序
- TypeError: connection.connect is not a function
- VR panorama truly restores the driving school environment, and VR live shows the hard power of the driving school
- VR全景婚礼给你别样的浪漫,记录婚礼的甜蜜瞬间
- 分享一下自己最近写的一个移动端项目积累的一些实用技巧
- 企业级代码静态测试工具Helix QAC——技术规格
猜你喜欢
随机推荐
Practice of importing SAS files with R language
ROS2学习笔记(六)从turtlesim学习ROS2动作
VR panoramic wedding gives you another kind of romance and records the sweet moment of the wedding
Ros2 learning notes (10) learn the workspace of ros2 from turnlesim
Male female pairing
R语言data.table导入数据实战:data.table设置键值(key)、复合键设置、删除键、设置键值之后的数据连接(join)更加方便、设置了键值之后可以使用keyby语法代替by语法
工作中有必要记录的知识点
A记录、MX记录、CNAME记录这些名词是什么意思?
The ABAQUS model of standardized steel box girder is established, and the plug-in of RSG is used for secondary development
[concurrent programming 055] will the following daemon thread execute the code in the finally module?
智慧文旅逐渐数字化,vr全景推动文旅一体化发展
Design and implementation of house leasing system based on J2EE Rar (paper + project source code + database file)
JS基础7
缩表牛:最后的狂欢
Local deployment of distributed monitoring cat server
这个开源项目是要把我笑死吗?
Ros2 learning notes (IX) learn the bag recording of ros2 from turnlesim
vr全景真实还原驾校环境,vr直播展现驾校硬实力
给自己成功的可能性
【生活杂谈】中体平台教你如何提高彩票中奖率









