1143. Longest Common Subsequence
Given two strings text1 and text2, return the length of the longest common subsequence of these two strings.
A subsequence of a character string refers to a new character string: it is a new character string formed by deleting some characters (or no characters) from the original string without changing the relative order of the characters.
For example, "ace" is a subsequence of "abcde", but "aec" is not a subsequence of "abcde". The "common subsequence" of two strings is the subsequence shared by the two strings.If the two strings have no common subsequence, 0 is returned.
The longest common subsequence (Longest Common Subsequence, abbreviated LCS
) is a very classic interview question, because its solution is typical 二维动态规划
, most of the more difficult string problems are the same as this question, for example 编辑距离
. Moreover, this algorithm can be used to solve other problems with a little modification, so the LCS algorithm is worth mastering.
For analysis, see this article " Classic Dynamic Programming: The Longest Common Subsequence "
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length(), n = text2.length();
int[][] dp = new int[m+1][n+1];
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(text1.charAt(i-1) == text2.charAt(j-1)){
dp[i][j] = 1 + dp[i-1][j-1];
}else {
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[m][n];
}
}
Save time by converting to character array
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
char[] t1 = text1.toCharArray();
char[] t2 = text2.toCharArray();
int m = t1.length;
int n = t2.length;
int[][] dp = new int[m+1][n+1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (t1[i-1] == t2[j-1]){
dp[i][j] = 1+ dp[i-1][j-1];
}else {
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[m][n];
}
}