LeetCode 1143.最長公共子序列(LCS)
雙序列型
確定狀態:
設字符串爲s1
和s2
,長度分別爲m
和n
。
此時LCS長度爲l
存在三種情況:
s1[i]
此時不在LCS中,是多餘的s2[j]
此時不在LCS中,是多餘的s1[i]==s2[j]
,此時l=l+1
狀態:設f[i][j]
爲s1
前i
個字符和s2
前j
個字符的LCS長度
轉移方程:
f[i][j]=max{ f[i-1][j],f[i][j-1], f[i-1][j-1]+1(s1[i]==s2[j]) }
初始條件:
和一般的序列型相同,前0個都爲0,f[i][0]=0,f[0][j]=0
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
char []s1=text1.toCharArray();
char []s2=text2.toCharArray();
int m=s1.length;
int n=s2.length;
if(m==0||n==0)
return 0;
int [][]f=new int[m+1][n+1];
int i,j;
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
f[i][j]=Math.max(f[i-1][j],f[i][j-1]);
if(s1[i-1]==s2[j-1])
f[i][j]=Math.max(f[i][j],f[i-1][j-1]+1);
}
}
return f[m][n];
}
}