Algorithm learning-Longest Common subsequence (LCS) C ++ implementation

Source: Internet
Author: User

Algorithm learning-Longest Common subsequence (LCS) C ++ implementation
Longest Common subsequence

The longest common subsequence is very simple, that is, to find the longest subsequence in two strings. Here we define two meanings:

Substring: a consecutive string of characters. Subsequence: A nonconsecutive string of characters.

So here we need to look for the discontinuous oldest sequence,

Dynamic Planning

Here, why do we need to use dynamic planning? To put it simply, dynamic planning is an algorithm to reduce the time complexity and apply for an additional space to save the results of each step, finally, find the optimal solution from these results.

There is a problem here: Generally, the current optimal solution is only related to the current time and the previous time, and has no relationship with other time, so that dynamic planning can take effect and reduce complexity.

Analyze LCS

In fact, LCS seems very troublesome and cannot find any idea. If brute-force cracking is required, it may take O (n ^ 4), and the idea of using dynamic planning for this question is also very simple, why is it difficult to find a solution than the previous problems?

It is because the previous dynamic planning problems, such as the problem of backpacking and production lines, are all results in one-dimensional array space and planned to a linear time. This question requires O (m * n) time Complexity and space complexity.

So it is actuallym*nBy comparison, you can save the current optimal solution each time.

Code Implementation Analysis

The problem is that the result we need is only the length? Or include this sequence string for output together.

See the figure below:

Here we can see thati*jThe content of this matrix includes not only the numerical value (the optimal solution of the current result), but also a direction arrow, which represents the direction we need to walk when backtracking. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vcd4ncjxwpsv50tto0sph1elo77gjtobbvbj21rwjrl/J0tTKudPDwb249rb + zqy + 2NXzo6zSsr/fingerprint = "Solution Analysis"> Solution Analysis

In fact, this topic is easy to understand in dynamic planning. A state transfer function.

This is easy to understand. When one of the strings is 0, it must be 0.

It is easy to understand when two characters are equal. For example:

abcdAndadcd, In TraversalcOnlyaEqual, that is, 1.
SocEqual, that isabcAndadcWhen matchingabAndadThe length1, This1YescAre they equal. That is, when they are equalc[i-1][j-1]Large1.

The next one is better understood. If they are not equal, is it sure to find the biggest comparison in the previous time.

Code

This Code only outputs the length of LCS, And I have stored the direction of the result array. If you want to traverse, just traverse the array from the back to the front.

//// Main. cpp // LCS // The Longest Common subsequence (LCS) /// Created by Alps on 15/8/23. // Copyright (c) 2015 chen. all rights reserved. // # include
  
   
Using namespace std;/** the length is not defined here. The input string is stored in string, and then the string. c_str () is used to convert the string into an array. I am not doing this for convenience. */# Ifndef MAX_LENGTH # define MAX_LENGTH 15 // defines the maximum length of a string # endifint MaxNum (int firstNum, int secondNum) {return firstNum> secondNum? FirstNum: secondNum;} // defines the array structure struct matrix {int num; int direct ;}; typedef matrix Matrix; int LCS (char * strA, char * strB, int lengthA, int lengthB, Matrix * resultMatrix []) {if (lengthA = 0 | lengthB = 0) {return 0 ;}for (int I = 0; I <lengthA; I ++) {for (int j = 0; j <lengthB; j ++) {resultMatrix [I] [j]. num = 0; // set the maximum value of all default values to 0 resultMatrix [I] [j]. direct = 1; // all the default directions are 0 oblique, 1,-1 left }}for (in T I = 0; I <lengthA; I ++) {for (int j = 0; j <lengthB; j ++) {if (strA [I] = strB [j]) {resultMatrix [I + 1] [j + 1]. num = resultMatrix [I] [j]. num + 1; resultMatrix [I + 1] [j + 1]. direct = 0;} else {resultMatrix [I + 1] [j + 1]. num = MaxNum (resultMatrix [I + 1] [j]. num, resultMatrix [I] [j + 1]. num); resultMatrix [I + 1] [j + 1]. direct = resultMatrix [I + 1] [j]. num> resultMatrix [I] [j + 1]. num? 1:-1 ;}}return resultMatrix [lengthA] [lengthB]. num;} int main (int argc, const char * argv []) {char * strA = (char *) malloc (sizeof (char) * MAX_LENGTH ); char * strB = (char *) malloc (sizeof (char) * MAX_LENGTH); scanf (% s, strA); scanf (% s, strB); int lengthA = (int) strlen (strA); int lengthB = (int) strlen (strB); Matrix * resultMatrix [lengthA + 1]; for (int I = 0; I <= lengthA; I ++) {resultMatrix [I] = (Matr Ix *) malloc (sizeof (struct matrix) * (lengthB + 1);} int max = LCS (strA, strB, lengthA, lengthB, resultMatrix); printf (% d, max); std: cout <Hello, World !; Return 0 ;}
  

Above.©Alps1992

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.