Outputs of the two longest common substring string and the longest common subsequence

Outputs of the two longest common substring string and the longest common subsequence. Solving two longest common substring of a string, and the longest common subsequence in a very close approach is dynamic programming. But there is something different in the recurrence equation.

 

Outputs of the two longest common substring string

#include <bits/stdc++.h>
using namespace std;

string LCS(string str1, string str2){
	if(str1.empty() || str2.empty()){
        return "";
    }
    
    int indexMax=0, maxn=0;
    vector<vector<int> > L(str1.size(), vector<int>(str2.size(),0) );   //全部初始化为0 
    //L[i][j]代表 str1[0~i-1]和str2[0~j-1] 的最长公共子串的长度   

    for(int i=0; i<str1.length(); i++){
        for(int j=0; j<str2.length(); j++){
            if(str1[i] == str2[j] ){
                if(i==0 || j==0){
                    L[i][j]=1;
                }
                else{
                    L[i][j]=L[i-1][j-1]+1; 
                }
            }
            // else is str1 [i]! = str2 [ j] in the case where, in this case L [i] [j] = 0, since the initialization has been set to 0, it is not written here. 

            After completion of the processing // L [i] [j], check whether recorded 
            IF (L [I] [J]> MAXN) { 
                MAXN = L [I] [J]; // record the longest common subsequence string length 
                indexMax = i; end position of the character "longest common substring" occurs at the time of recording // 
            } 
        } 
    } 
    return str1.substr (indexMax +. 1-MAXN, MAXN);    
    // string has a length, taken (end-start + 1) = maxn, then = End +. 1-Start MAXN   
    // indexMax - (+ indexMax-MAXN. 1). 1 = + MAXN, MAXN length string that is taken. 
}   

Int main () { 
	String str1, str2; 
	String CUR; 
	the while (getline (CIN, CUR)) { 
		IF (str1.empty ()) str1 = CUR; 
		the else IF (str2.empty ()) = str2 CUR;
		
		if(!str1.empty() && !str2.empty() ){  
			cout<< LCS(str1, str2) <<endl;
			
			str1.clear();
			str2.clear();
		}
		cur.clear();
	} 	
} 

  

 

Two output strings longest common subsequence. And the difference between common subsequence common substrings that do not require continuous sequence, which is required substring in the original string is continuous.

 

Guess you like

Origin www.cnblogs.com/liugl7/p/11300442.html