找出X={x1,x2,x,3,x4,x5…….} Y={y1,y2,y3,y4……}最长公共字串
    由最优子结构性质可建立递归关系如下:

    Screenshot_20220323_002849.jpg

    Screenshot_20220322_202013_tv.danmaku.bili_edit_583323768797573.jpg
    Screenshot_20220322_201606_tv.danmaku.bili_edit_583301227321540.jpg

    1. #include<iostream>
    2. using namespace std;
    3. void LSCLengh(int m, int n, char x[], char y[]) {
    4. //m是x数组长度
    5. //n是y数组长度
    6. //c[m+1][n+1]数组是辅助空间,记录
    7. int c[7 + 1][6 + 1];//辅助空间
    8. int i, j;
    9. int p=0;//记录公共子串末尾位置,如果要输出公共字串:(Xp-len+1,Xpmax)
    10. int len=0;//记录公共字串长度
    11. for (i = 0; i <= m; i++)
    12. c[i][0] = 0;
    13. for (i = 1; i <= n; i++)
    14. c[0][i] = 0;//边缘初始化
    15. for (i = 1; i <= m; i++) {
    16. for (j = 1; j <= n; j++)
    17. {
    18. if (x[i - 1] == y[j - 1])
    19. {
    20. c[i][j] = c[i - 1][j - 1] + 1;
    21. if (c[i][j] > len) {
    22. len = c[i][j];
    23. p = i;
    24. }
    25. }
    26. else{
    27. c[i][j] = 0;
    28. }
    29. }
    30. }
    31. cout << endl;
    32. for (i = 0; i <= m; i++) {
    33. cout << " ";
    34. for (j = 0; j <= n; j++)
    35. cout << c[i][j] << " ";
    36. cout << endl;
    37. }
    38. cout << " 公共子串末尾位置:p=" << p << endl;
    39. cout << " 公共字串长度:len=" << len << endl << " 公共字串为:";
    40. for (i = p - len + 1; i <= p; i++)
    41. cout << x[i-1];
    42. cout << endl;
    43. }
    44. int main() {
    45. char x[] = { 'A','B','C','A','D','B','B' };
    46. char y[] = { 'B','C','E','D','B','B' };
    47. LSCLengh(7, 6, x, y);
    48. return 0;
    49. }

    运行结果:
    image.png