# LCS Oldest string problem

Source: Internet
Author: User

Method One: Dynamic planning efficiency O (MN) (MN is the length of two strings respectively)

`#include <iostream>using namespace Std;int c[100][100];//Global variables are automatically initialized to 0inline int max (int a, int b) {return (a > B? a : b);} int LCS (const char *x,const char *y) {if (NULL = = X | | NULL = = Y) return 0;int Xlen = strlen (X), int ylen = strlen (y), for (int i = 1, i <= Xlen; i++) {for (int j = 1; J <= YL En J + +) {if (x[i] = = Y[j]) c[i][j] = C[i-1][j-1] + 1;elsec[i][j] = max (c[i][j-1], c[i-1][j]);}} return C[xlen][ylen];} int main () {char a[8] = "Abcbdab"; char b[8] = "Bdcabab"; cout << LCS (A, B) << endl;system ("pause"); return 0;}`

Method Two: Inefficient recursive algorithm

`#define INF 9999999int c[100][100];int lcs_memo (const char* X, const char* y,int i,int j) {if (C[i][j] < INF) return C[i] [J];if (0 = = I | | 0 = = j) C[i][j] = 0;else if (x[i-1] = = Y[j-1]) c[i][j] = Lcs_memo (x,y,i-1, j-1) + 1;else{int p = L Cs_memo (x, Y, I-1, j); int q = Lcs_memo (x, Y, I, j-1); if (P >q) c[i][j] = p;else{c[i][j] = q;}} return c[i][j];} int LCS (const char* x, const char* Y) {if (NULL = = X | | NULL = = Y) return 0;int Xlen = strlen (X), int ylen = strlen (Y), memset (c, INF, sizeof (c));//Note that each byte is assigned a value of INF, not a intreturn Lcs_ Memo (X, Y, Xlen, Ylen);} int main () {char a[8] = "Abcbdab"; char b[8] = "Bdcabab"; cout << LCS (A, B) << endl;system ("pause"); return 0;}`

LCS Oldest string problem

Related Keywords:

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.