gpt4 book ai didi

algorithm - LCS 算法(示例)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:19:55 24 4
gpt4 key购买 nike

有一个动态规划算法可以找到两个序列的最长公共(public)子序列。如何找到两个序列X和Y的LCS算法。(正确性测试)

(a)   X  = ABEDFEESTYH  Y=ABEDFEESTYHABCDF

(b) X = BFAAAABBBBBJPRSTY Y=ABCDEFGHIJKLMNOPRS

(c) X = ϕ (Empty Sequence), Y = BABADCAB

最佳答案

这是一个在线计算器

http://igm.univ-mlv.fr/~lecroq/seqcomp/node4.html

Java

public class LCS {

public static void main(String[] args) {
String x = StdIn.readString();
String y = StdIn.readString();
int M = x.length();
int N = y.length();

// opt[i][j] = length of LCS of x[i..M] and y[j..N]
int[][] opt = new int[M+1][N+1];

// compute length of LCS and all subproblems via dynamic programming
for (int i = M-1; i >= 0; i--) {
for (int j = N-1; j >= 0; j--) {
if (x.charAt(i) == y.charAt(j))
opt[i][j] = opt[i+1][j+1] + 1;
else
opt[i][j] = Math.max(opt[i+1][j], opt[i][j+1]);
}
}

// recover LCS itself and print it to standard output
int i = 0, j = 0;
while(i < M && j < N) {
if (x.charAt(i) == y.charAt(j)) {
System.out.print(x.charAt(i));
i++;
j++;
}
else if (opt[i+1][j] >= opt[i][j+1]) i++;
else j++;
}
System.out.println();

}

}

关于algorithm - LCS 算法(示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8257655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com