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

最长公共子序列(一)

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];
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 11:30
点赞 评论 收藏
分享
写不来代码的小黑:这么小的城市能有做it的公司也不容易
点赞 评论 收藏
分享
强大的马里奥:不太可能,我校计算机硕士就业率99%
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务