首先说一下最长公共子序列和最长公共子串的区别就是前者可以不连续,后者一定是连续的,比如abcde和abced,他的最长公共子序列是abcd或者abce(长度为4),而他们的最长公共子串只abc(长度为3)。

       这两个虽然是两个名字,但这都是LCS(Longest Common Subsequence)问题,是很经典的动态规划问题,以NYOJ的一道题为例:传送门

       对于最长公共子序列,最简单粗暴的方式就是暴力递归求解,还有就是利用二维数组dp对str1[i],str2[j]的状态来存长度。而dp最主要的就是状态转移方程



代码实现

#include <iostream>                     /* 最长公共子序列 */
#include <cstdio>
#include <cstring>
using namespace std;
int n;
int dp[1005][1005];
string str1,str2;

int main()
{
	scanf("%d",&n);
	while(n--){
		cin>>str1>>str2;
		int len1 = str1.length();
		int len2 = str2.length();
		memset(dp,0,sizeof(dp));      // 清空数组
		for(int i=1;i<=len1;i++){
			for(int j=1;j<=len2;j++){
				if(str1[i-1] == str2[j-1])
					dp[i][j] = dp[i-1][j-1] + 1;
				else
					dp[i][j] = dp[i-1][j] > dp[i][j-1] ? dp[i-1][j] : dp[i][j-1];
			}
		}
		printf("%d\n",dp[len1][len2]);
	}
	return 0;
}


       对于最长公共子串的状态转移方程来说,因为子串必须是要连续的,所以当str1[i-1]!=str2[j-1]的时候dp[i][j]的状态应该为0,最后我们还需要定义一个变量来记录dp[i][j]中的最大值,即为最长公共子串的长度。



代码实现

#include <iostream>              /* 最长公共子串 */
#include <cstdio>
#include <cstring>
using namespace std;
int n;
int dp[1005][1005];
string str1,str2;

int main()
{
	scanf("%d",&n);
	while(n--){
		cin>>str1>>str2;
		int len1 = str1.length();
		int len2 = str2.length();
		memset(dp,0,sizeof(dp));
    int temp  = 0;
		for(int i=1;i<=len1;i++){
			for(int j=1;j<=len2;j++){
      if(str1[i-1] == str2[j-1]){
          dp[i][j] = dp[i-1][j-1] + 1;
          temp = max(dp[i][j],temp);
        }
        else{
          dp[i][j] = 0;
        }
			}
		}
		printf("%d\n",temp);
	}
	return 0;
}

          建议按照动态转移方程手动模拟一下dp存长度的过程。