目录
最长公共子串
描述
给定两个字符串str1和str2,输出两个字符串的最长公共子串,
题目保证str1和str2的最长公共子串存在且唯一
扫描二维码关注公众号,回复:
13161617 查看本文章
示例1
输入
"1AB2345CD","12345EF"
返回值
"2345"
备注:
方法:动态规划
import java.util.*;
public class Solution {
public String LCS (String str1, String str2) {
// write code here
int len_str1=str1.length(),len_str2=str2.length();
int dp[][]=new int[len_str1+1][len_str2+1];
int max=0,index=0;
for (int i = 0; i < len_str1; i++) {
for (int j = 0; j < len_str2; j++) {
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?str1.substring(index-max,index):"";
}
}