1. 题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f1bc3516af63f2004367d8143388a9c6.png#pic_center)
2. 思路
(1) 动态规划
- dp[i][j]表示str1中以下标i-1结尾的子字符串和str2中以下标j-1结尾的子字符串的最长公共子串。
- 若chars1[i-1]==chars2[j-1],则dp[i][j]=dp[i-1][j-1]+chars1[i-1],同时,更新全局最长公共子串;否则,dp[i][j]=""。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public String LCS(String str1, String str2) {
char[] chars1 = str1.toCharArray();
char[] chars2 = str2.toCharArray();
int n1 = str1.length();
int n2 = str2.length();
String[][] dp = new String[n1 + 1][n2 + 1];
for (int i = 0; i < n1; i++) {
dp[i][0] = "";
}
for (int i = 0; i < n2; i++) {
dp[0][i] = "";
}
String res = "";
for (int i = 1; i <= n1; i++) {
for (int j = 1; j <= n2; j++) {
if (chars1[i - 1] == chars2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + chars1[i - 1];
if (dp[i][j].length() > res.length()) {
res = dp[i][j];
}
} else {
dp[i][j] = "";
}
}
}
return res;
}
}