欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

最长公共子序列

程序员文章站 2022-07-16 11:46:00
...

题目:牛客网链接

解题思路:(图片来源:https://www.cnblogs.com/hapjin/p/5572483.html

最长公共子序列

 最长公共子序列

最长公共子序列

import java.util.Scanner;

public class Main {
	public static int longestCommonSubsquence(String str1, String str2){
        //第一行和第一列要置0
		int m = str1.length()+1;
		int n = str2.length()+1;
		int[][] dp = new int[m][n];
		for(int i = 0; i < m; i++){
			for(int j = 0; j < n ; j++){
                //第一行和第一列要置0
				if(i == 0 || j == 0)
					dp[i][j]=0;
				else 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][j-1], dp[i-1][j]);
				}
			}
		}
		return dp[m-1][n-1];
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		while(in.hasNext()){
			String str1 = in.next();
			String str2 = in.next();
			System.out.println(longestCommonSubsquence(str1, str2));
		}

	}

}

 

 

相关标签: 动态规划