lcs
刚刚重新学了一种模板。
#include<bits/stdc++.h> using namespace std; int fcs(const char *ts1,const char *ts2,string & str){//参数传入char * 和引用 int l1 = strlen(ts1); int l2 = strlen(ts2); const char * s1 = ts1 - 1;//这里用于将char数组前移一位,方便后面操作。下标1对应第一个char const char * s2 = ts2 - 1; int m[101][101] = {0}; int i,j; for(i = 1;i <= l1;i++){ for(j = 1; j <= l2;j++){ m[i][j] = max(m[i-1][j],m[i][j-1]); if(s1[i] == s2[j]){ m[i][j] = max(m[i][j],m[i-1][j-1]+1); } } }
//后面求出最长公共子序列 i = l1,j = l2; while(i != 0 && j!=0 ){ if(s1[i] == s2[j]){ str.push_back(s1[i]); i--; j--; }else{ if(m[i-1][j] > m[i][j-1]){ i--; }else{ j--; } } } reverse(str.begin(),str.end()); return m[l1][l2];//返回长度 } int main() { const char *s1 = "abcdef"; const char *s2 = "bcdefg"; string s; cout << fcs(s1,s2,s) << endl; cout << s << endl; return 0; }