【LeetCode练习】[中等]1143. 最长公共子序列

【LeetCode练习】[中等]1143. 最长公共子序列

1143. 最长公共子序列

1143. 最长公共子序列

算法思想:字符串,动态规划

题目:

在这里插入图片描述
分析:
在这里插入图片描述

java代码

class Solution {
    
    
    //运用动态规划知识
    public int longestCommonSubsequence(String text1, String text2) {
    
    
		int M = text1.length();
		int N = text2.length();
		int[][] dp = new int[M+1][N+1];//dp数组
		for (int i = 1; i < M+1; i++) {
    
    
			for (int j = 1; j < N+1; j++) {
    
    
                //状态转移矩阵
				if (text1.charAt(i-1) == text2.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][N];//返回最后一个格子
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39457586/article/details/109773884