题解 | #最长公共子序列(一)#

最长公共子序列(一)

http://www.nowcoder.com/practice/672ab5e541c64e4b9d11f66011059498

import java.util.*;

public class Main {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt(), n = sc.nextInt();
        sc.nextLine();
        String s1 = sc.nextLine(), s2 = sc.nextLine();
        System.out.println(dp(m, n, s1, s2));
    }
    
    public static int dp(int m, int n, String s1, String s2) {
        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]);
                }
            }
        }
        return dp[m][n];
    }
}
全部评论

相关推荐

点赞 2 评论
分享
牛客网
牛客企业服务