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