给定两个字符串str1和str2,输出两个字符串的最长公共子串
题目保证str1和str2的最长公共子串存在且唯一。
package collection;
public class HashMapDemo01 {
public static void main(String args[]) {
System.out.println(DP(
"d8Wt20lnSgAw0HgauN2Kspyr298H6wQWMO3tMNRpWmR25NNTD4VTnq16LX80khSMEG0W5V72cIDLvy0WB1Nfnz4z51qrGNKT3xImT141NY92514w8AF5q1sul7MVNFZnGengc03vO912lFftHDkWpMwWN0SY4pXO1QLji18ujkZV4vr449Wo495WOyIXiO4C9M5L7hQ4tX9ePvV5ohnX00e4mOW28xO968cdR266Ej5M",
"MV3Et2Q4x4YFlN304p5oLJzVT5zdfz8X83srj64mAx18Ai8kE82aF4so17uR3tD7Nch9CO775WHeVD166zgogKQAj4y04EjJ6Mc23Uvmt11NY92514w8AF5q1sul7MVNFZndJq1vh7qx45XOwP1k1M9jsbB3MLc9FFoy825lu0Cs9Bh3Xm84p5C36r6USQrF96W0b05RfF308001LpK89056qQ8517YFj4pM"));
}
// 动态规划
public static String DP(String str1, String str2) {
if (str1 == null || str2 == null)
return "-1";
int maxLen = 0;
int index = 0;
int row = str1.length() + 1;
int col = str2.length() + 1;
int[][] dp = new int[row][col];
for (int i = 1; i <= str1.length(); i++) {
for (int j = 1; j <= str2.length(); j++) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = 0;
}
if (maxLen <= dp[i][j]) {
maxLen = dp[i][j];
index = i - 1;
}
}
}
return maxLen == 0 ? "-1" : str1.substring(index - maxLen + 1, index + 1);
}
}