The longest common substring, the longest common subsequence--recursive dynamic programming

The longest common substring and the longest common
subsequence There is a similar method to solve the longest common substring and the longest common subsequence recursively. Loop through the matrix method to find the same value for two strings. When finding the same character, the value at the corresponding matrix position is the upper left position value plus one. It's just that finding the longest common subsequence requires one more step than finding the longest common subsequence, that is, when the characters are not the same, the corresponding matrix position must be the larger value of the left and top.
The state res(i)(j) is the optimal number of common substrings between the first i characters in the previous string and the first j characters in the next string. When the two characters are the same, the state transition equation is: res (i)(j)=res(i-1)(j-1)+1
and the longest common subsequence has a feature, that is, there can be differences between the same characters, as long as the position order is unchanged That is, it is transitive . When the two characters are not the same, the state transition equation is:
res(i)(j)=max(res(i-1)(j),res(i)(j-1) ))

The code is as follows: the
longest common substring:

#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
    
    
 int res[50][50];
 int i,j,k,max_s=0;
 string a,b;
 cin>>a>>b;
 memset(res,0,sizeof(res));
 for(i=1;i<=a.size();i++)
 {
    
    
  for(j=1;j<=b.size();j++)
  {
    
    
   if(a[i-1]==b[j-1])
   {
    
    
    res[i][j]=res[i-1][j-1]+1;
    if(res[i][j]>max_s)
    {
    
    
     max_s=res[i][j];
    }
   }
   else {
    
    
    res[i][j]=max(res[i-1][j],res[i][j-1]);
   }
  }
 }
 cout<<max_s<<endl;
 /*
 for(i=0;i<=a.size();i++)
 {
  for(j=0;j<=b.size();j++)
  {
   cout<<res[i][j]<<" ";
  }
  printf("\n");
 }
 */
 return 0;
}

The longest common subsequence:

#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
    
    
 int res[50][50];
 int i,j,k,max_s=0;
 string a,b;
 cin>>a>>b;
 memset(res,0,sizeof(res));
 for(i=1;i<=a.size();i++)
 {
    
    
  for(j=1;j<=b.size();j++)
  {
    
    
   if(a[i-1]==b[j-1])
   {
    
    
    res[i][j]=res[i-1][j-1]+1;
    if(res[i][j]>max_s)
    {
    
    
     max_s=res[i][j];
    }
   }
   else {
    
    
    res[i][j]=max(res[i-1][j],res[i][j-1]);
   }
  }
 }
 cout<<max_s<<endl;
 /*
 for(i=0;i<=a.size();i++)
 {
  for(j=0;j<=b.size();j++)
  {
   cout<<res[i][j]<<" ";
  }
  printf("\n");
 }
 */
 return 0;
}

Guess you like

Origin blog.csdn.net/HT24k/article/details/105682936