Programming Algorithm-Longest Common subsequence (LCS) code (c)

Source: Internet
Author: User
Longest Common subsequence (LCS) code (c)


Address: http://blog.csdn.net/caroline_wendy


Question: Given two strings S and T, find the length of the longest common subsequences of the two strings. the subsequences of the strings must be continuous and can contain intervals.

That is, the longest public subsequence problem (LCS, Longest Common subsequence)


UseDynamic Planning, SupposeEqual characters, Two stringsIncrement by oneUntil the end of the string.


Code:

/* * main.cpp * *  Created on: 2014.7.17 *      Author: spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <memory.h>#include <limits.h>#include <utility>#include <queue>#include <algorithm>using namespace std;class Program {static const int MAX_N = 100;int n=4, m=4;char s[MAX_N] = "abcd", t[MAX_N] = "becd";int dp[MAX_N+1][MAX_N+1];public:void solve() {for (int i=0; i<n; i++) {for (int j=0; j<m; j++) {if (s[i]==t[j]) {dp[i+1][j+1] = dp[i][j]+1;} else {dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);}}}printf("result = %d\n", dp[n][m]);}};int main(void){Program P;P.solve();    return 0;}


Output:

result = 3








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.