当前位置:网站首页>最长公共子串
最长公共子串
2022-08-02 03:33:00 【小艾菜菜菜】
算法——最长公共子串(一张图片看懂)
概述
给定str1与str2两个字符串,找出其中最长的公共子串。
思路
用str1和str2建立一个二维矩阵,很轻易的就能从中发现关系。矩阵的大小为:
int[][] dp = new int[str1.lenth()+1][str2.length()+1]
- 1
这是为了方便substring的操作而已。
下面给出图示方便理解:
代码
public class 最长公共子串 {
/** * longest common substring * @param str1 string字符串 the string * @param str2 string字符串 the string * @return string字符串 * 将str1与str2组成一个二维矩阵,相同的地方标记为1,那么可以观察到对角线处相连的1就是一个连续的公共子串; * 为了搞到最大的值,则只需要将对角线的1不断地累加并保存即可,待矩阵构建完毕,我们就已经知道最大的子串长为多少, * 以及在哪个index结束。 */
public String LCS (String str1, String str2) {
//异常处理
if (str1 == null || str2 == null)
return str1 == null ? str2 : str1;
//动态规划
int len1 = str1.length(),
len2 = str2.length(),
max = 0,
index = 0;
int[][] dp = new int[len1 + 1][len2 + 1];
for (int i = 0; i < len1; i++){
for (int j = 0; j < len2; j++){
//如果字符相等,则这个子串的长度取决于之前的子串长度 + 1
if (str1.charAt(i) == str2.charAt(j)){
dp[i + 1][j + 1] = dp[i][j] + 1;
}
if (max < dp[i + 1][j + 1]){
max = dp[i + 1][j + 1];
index = i + 1;
}
}
}
//截取字符串并返回
return max == 0 ? "-1" : str1.substring((index - max),(index));
}
}
边栏推荐
猜你喜欢
随机推荐
开源代码交叉编译操作流程及遇到的问题解决(lightdm)
发布全新的配置格式 - AT
Process (below): process control, termination, waiting, replacement
【LeetCode】设计链表
联阳(ITE)IT66021FN:HDMI转RGB芯片 3D 资料
Comparison between Boda Industrial Cloud and Alibaba Cloud
剑指Offer 34.二叉树中和为某一值的路径 dfs+回溯
Type c PD 电路设计
GM7150,振芯科技,视频解码器,CVBS转BT656/601,QFN32,替换TVP5150/CJC5150
步兵相关连接
【TCS3200 color sensor and Arduino realize color recognition】
Introduction and mock implementation of list:list
MIPI解决方案 ICN6202:MIPI DSI转LVDS转换芯片
【nRF24L01 connects with Arduino to realize wireless communication】
GM7150 CVBS转BT656视频解码芯片详细内容及设计要求
bluez5.50+pulseaudio实现蓝牙音响音频播放
IoT solution
剑指Offer 32.Ⅲ从上到下打印二叉树
【LeetCode】Add the linked list with carry
IDEA2021.2安装与配置(持续更新)









