【动态规划】最长公共子序列问题 LCS

状态转移方程

可以通过excle表看来理解状态转移方程。将字符串的长度作为表格长和宽。然后开始手算,算一遍相信你就理解了
dp数组

if(两个字符相等)
dp[i][j] = dp[i-1][j-1]+1;
else
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);

注意越界

用例:
123123456
123333456

代码

import java.util.Scanner;

public class Main {
    static Scanner in = new Scanner(System.in);

    public static void main(String args[]) {
        String str1 = in.next();
        String str2 = in.next();
        int dp[][] = new int[str1.length()+1][str2.length()+1];
        for (int i = 1; i <= str1.length() ; i++) {
            for (int j = 1; j <= str2.length(); j++) {
                if (str1.charAt(i-1) == str2.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]);
            }
        }
        System.out.println(dp[str1.length()][str2.length()]);
    }
}

猜你喜欢

转载自blog.csdn.net/HuaLingPiaoXue/article/details/88694037