題目描述:
最長公共子序列(Longest Common Subsequence,簡稱 LCS)是一道非常經典的面試題目,因爲它的解法是典型的二維動態規劃,大部分比較困難的字符串問題都和這個問題一個套路,比如說編輯距離。而且,這個算法稍加改造就可以用於解決其他問題,所以說 LCS 算法是值得掌握的。
題目就是讓我們求兩個字符串的 LCS 長度:
輸入: str1 = “abcde”, str2 = “ace”
輸出: 3
解釋: 最長公共子序列是 “ace”,它的長度是 3
dp數組表:
AC代碼:
//最長公共子序列
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
char str1[100],str2[100];
int dp[100][100];
int main()
{
int i,j;
//dp[i][j]:代表不超過兩個數組中的第i個和第j個索引位置時,最長的公共子序列的長度
cin>>str1>>str2;
int n=strlen(str1);
int m=strlen(str2);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(str1[i]==str2[j])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
cout<<dp[n-1][m-1]<<endl;
return 0;
}