Given two strings text1 and text2, return the length of the longest common subsequence of the two strings. If no common subsequence exists, return 0. A subsequence of a string is a new string made up of the original string without changing the relative order of the characters by deleting some characters (or none). For example, "ace" is a subsequence of "ABCDE", but "AEC" is not a subsequence of "ABCDE". A common subsequence of two strings is a subsequence that is shared by both strings. Example 1: Input: text1 = "abcde", text2 = "ace" Output: 3 Explanation: The longest common subsequence is "ace", which has length 3. Example 2: Input: text1 = "ABC ", text2 =" ABC "Output: 3 Explanation: The longest common subsequence is" ABC ", which has length 3.Copy the code
class Solution { public int longestCommonSubsequence(String text1, String text2) { int m = text1.length(), n = text2.length(); Int [][] dp = new int[m+1][n+1]; int[] dp = new int[m+1][n+1]; for(int i = 1; i <= m; i++){ char s = text1.charAt(i-1); for(int j = 1; j <= n; j++){ char d = text2.charAt(j-1); If (s == d){dp[I][j] = dp[i-1][j-1]+1; if(s == d){dp[i-1][j-1]+1; } else {/ / if the range, it is to take the element and the maximum value of the above elements to the left of the dp [I] [j] = math.h Max (dp [j], [I - 1] dp [I] [1]). Return dp[m][n]; }}Copy the code