当前位置:网站首页>最长公共子串
最长公共子串
2022-04-22 01:45:00 【河工大某某】
描述
给定两个字符串str1和str2,输出两个字符串的最长公共子串
题目保证str1和str2的最长公共子串存在且唯一。
数据范围: 1 \le |str1|,|str2| \le 50001≤∣str1∣,∣str2∣≤5000
要求: 空间复杂度 O(n^2)O(n2),时间复杂度 O(n^2)O(n2)
示例1
输入:
"1AB2345CD","12345EF"
复制返回值:
"2345"
复制
备注:
1 \leq |str_1|, |str_2| \leq 5\,0001≤∣str1∣,∣str2∣≤5000
import java.util.*;
public class Solution {
/**
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
public String LCS (String str1, String str2) {
// write code here
int[][] mat = new int[str1.length() + 1][str2.length() + 1];
int maxLen = 0;
int lastIdx = 0;
for(int i = 1; i < mat.length; i++) {
for(int j = 1; j < mat[0].length; j++) {
if(str1.charAt(i - 1) == str2.charAt(j - 1)) {
mat[i][j] = mat[i - 1][j - 1] + 1;
if(mat[i][j] > maxLen) {
maxLen = mat[i][j];
lastIdx = i;
}
} else {
mat[i][j] = 0;
}
}
}
StringBuilder sb = new StringBuilder();
for(int j = lastIdx - maxLen; j < lastIdx; j++) {
sb.append(str1.charAt(j));
}
return sb.toString();
}
}
版权声明
本文为[河工大某某]所创,转载请带上原文链接,感谢
https://blog.csdn.net/diOSyu/article/details/124299639
边栏推荐
- Common evaluation indexes of medical image segmentation
- Code source daily question div1 (401-407)
- Codeforces Round #783 (Div. 2)
- Bsides-vancouver-2018-workshop target penetration test
- 经济学人翻译练习4.16期刊——美国国税局
- 代码源每日一题 div1 (301-307)
- 阿里专家原创,自学编程找工作
- vscode使用ssh远程连接失败
- 【Swing中的几种常用按钮】
- DVWA series - XSS (cross site script injection (reflective, storage, DOM))
猜你喜欢
![[server data recovery] successful cases of data recovery after the server is flooded](/img/b4/069c0b699e6bd6c4fc508e3178ec57.jpg)
[server data recovery] successful cases of data recovery after the server is flooded

Alibaba Android development specification, senior programmer interview questions

Station B charging | charging more than 1500 a week, Yinfa up is the new dark horse of station B?

DVWA系列——File Upload(文件上传)

QT campus barter system

mysql实现主从复制/主从同步

Bluemoon target penetration test

【ing】MATLAB工具包-Dynamic Copula Toolbox 3.0详解

Realization of multivariate normal copula distribution with MATLAB

Test d'automatisation de l'extrémité mobile appium - - mise en place d'un simulateur et d'un environnement réel
随机推荐
B站充电|单周充电超1500,银发UP主成B站新黑马?
医学图像分割常见评测指标
Network protocol analysis summary
The idea window cannot be found in multi screen mode
如何调用EasyCVR平台的登录、播放地址、录像回看接口?
Memory leak caused by C UserControl
MATLAB实现多元正态Copula分布
oracle安装server端
【DFS】【剪枝】小猫爬山
Ali expert original, self-taught programming, looking for a job
点云分割(point cloud segmentation)任务笔记
经济学人翻译练习4.16期刊——美国国税局
Floyd finding the minimum ring template
阿里大牛整理,android面试选择题
[server data recovery] successful cases of data recovery after the server is flooded
Fundamentals lecture 30 Lecture 9 geometric application of univariate function integration
VMware虚拟机安装详细教程网络NAT、网桥配置
代码源每日一题 div1 (301-307)
真羡慕哪些不用发朋友圈的人
[shell] training script (updated from time to time)