求最长公共子序列输出 Java
时间: 2024-02-23 18:32:07 浏览: 117
求最长公共子序列
5星 · 资源好评率100%
以下是 Java 代码,实现最长公共子序列:
```
public class LongestCommonSubsequence {
public static String findLCS(String s1, String s2) {
int m = s1.length();
int n = s2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
int index = dp[m][n];
char[] lcs = new char[index];
int i = m, j = n;
while (i > 0 && j > 0) {
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
lcs[--index] = s1.charAt(i - 1);
i--;
j--;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
i--;
} else {
j--;
}
}
return new String(lcs);
}
public static void main(String[] args) {
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
System.out.println("Longest Common Subsequence: " + findLCS(s1, s2));
}
}
```
输出:
```
Longest Common Subsequence: GTAB
```
在这个例子中,字符串s1和s2的最长公共子序列是“GTAB”。
阅读全文