- Longest Common Subsequence
Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, “ace” is a subsequence of “abcde” while “aec” is not). A common subsequence of two strings is a subsequence that is common to both strings.
If there is no common subsequence, return 0.
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
//字符串为null或长度为0,不可能有公共部分
if(text1 == null || text1.length() == 0) return 0;
if(text2 == null || text2.length() == 0) return 0;
//动态规划,考虑到0到i的text1和0到j长度的text2取最大公共子序列,如果text1.charAt(i) == text2.charAt(j), 取0到i-1的text1子串和0到j-1的text2子串的最大公共子序列值+1,如果不等,那就直接取这个最大公共子序列长度
int len1 = text1.length(), len2 = text2.length();
int[][] dp=new int[len1+1][len2+1];
//还是要把i=0和j=0的情况先写完
for(int i=0;i<len1+1;i++){
dp[i][0] = 0; //text2为空
}
for(int j=0;j<len2+1;j++){
dp[0][j] = 0; //text1为空
}
for(int i=1;i<len1+1;i++){
for(int j=1;j<len2+1;j++){
if(text1.charAt(i-1) == text2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1]+1;
}else{
//这里要取单独减一的最大值,因为dp[i-1][j]和dp[i][j-1]一定大于等于dp[i-1][j-1]
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[len1][len2];
}
}