使用字符串DP | #最长公共子序列(二)#
最长公共子序列(二)
https://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11
public class Solution { public String LCS (String s1, String s2) { int n1 = s1.length(), n2 = s2.length(); String[][] dp = new String[n1 + 1][n2 + 1]; for (int i = 0; i <= n1; i++) { Arrays.fill(dp[i], ""); } for (int i = 1; i <= n1; i++) { for (int j = 1; j <= n2; j++) { int maxDpI = i, maxDPj = j - 1; if (dp[i - 1][j].length() > dp[i][j - 1].length()) { maxDpI = i-1; maxDPj = j; } if (s1.charAt(i - 1) == s2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + s1.charAt(i - 1); } else { dp[i][j] = dp[maxDpI][maxDPj]; } } } return dp[n1][n2].equals("") ? "-1" : dp[n1][n2]; } }