class CommonOrder { static StringBuffer s1;// save string1 static StringBuffer s2;// save string2 static StringBuffer s3;// save commom string CommonOrder(String str1,String str2) { s1=new StringBuffer(str1); s2=new StringBuffer(str2); s3=new StringBuffer(); } /* 你编写的subsequenceOrder()函数的代码将被嵌在这里 */ StringBuffer getCommonString(){ return s3; } } public class Main{ public static void main(String[] args) { String X = null,Y = null; Scanner sc=new Scanner(System.in); if(sc.hasNext()) X=sc.nextLine(); if(sc.hasNext()) Y=sc.nextLine(); CommonOrder co=new CommonOrder(X,Y); co.subsequenceOrder(); StringBuffer str=co.getCommonString(); System.out.println(str+" "+str.length()); } }
时间: 2023-11-27 15:52:53 浏览: 63
以下是subsequenceOrder()函数的代码,它将找到s1和s2的最长公共子序列,并将其存储在s3中:
```
class CommonOrder {
static StringBuffer s1;// save string1
static StringBuffer s2;// save string2
static StringBuffer s3;// save commom string
CommonOrder(String str1, String str2) {
s1 = new StringBuffer(str1);
s2 = new StringBuffer(str2);
s3 = new StringBuffer();
}
void subsequenceOrder() {
int m = s1.length();
int n = s2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
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];
int i = m, j = n;
while (i > 0 && j > 0) {
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
s3.append(s1.charAt(i - 1));
i--;
j--;
index--;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
i--;
} else {
j--;
}
}
s3.reverse();
}
StringBuffer getCommonString() {
return s3;
}
}
```
该算法使用动态规划来找到s1和s2的最长公共子序列。在找到最长公共子序列之后,它将反转s3,以便输出正确的顺序。
阅读全文