C 學習字串最長公共子串行(非連續)演算法

2021-07-24 18:18:59 字數 1350 閱讀 3043

#include "stdafx.h"

#include

#include

#include

#include

#include

using

std::cin;

using

std::cout;

using

std::reverse;

using

std::endl;

using

std::max;

using

std::string;

using

std::vector;

//計算字串str1和str2的最長公共子串行

void lrc(string str1, string str2, string &resultstr)

//初始化第0列

for (int i = 0; i < len1; i++)

/*計算表示式

|-- result[i-1,j-1] + 1 x[i] == y[j]

resultvector[i][j] =|

|-- max(result[i-1,j],result[i,j-1] x[i] != y[j]

*///str1

for (int i = 1; i < len1 + 1; i++)

//x[i] != y[j]

else }}

//輸出結果矩陣

cout

<< "計算中間結果矩陣: "

<< endl;

cout

<< "\t\t";

for (int i = 0; i < len2; i++)

cout

<< str2.at(i) << "\t";

cout

<< endl;

for (int i = 0; i < len1+1; i++)

cout

<< endl;

}//計算公共子串行

while (len1 != 0 && len2 != 0)

else

if (resultvector[len1][len2 - 1] > resultvector[len1 - 1][len2])

else

}//字串翻轉

最長公共字串和最長公共子串行

給出兩個字串,找到最長公共子串,並返回其長度。建立乙個矩陣來儲存兩個字串出現相同字元的地方,比如 abccd 和 abcefc 就有 abccd a10000 b02000 c00300 e00040 f00000 c00100 這樣就有每次遇到相等的都加上下他的斜上方的位置的值,然後使用乙個max...

字串中最長公共子串行和最長公共子串

例 bdcaba和abcbdab,最長公共子串行為 bcba。dp解法 字串1的長度為length1,字串2的長度為length2,建立乙個二維陣列c length1 length2 用來記錄最長公共子串行的長度,狀態轉移方程為 整個狀態轉移以及二維陣列矩陣c為 生成字串長度加1的0矩陣,m用來儲存...

最長公共子串行 最長公共子串

1 最長公共子串行 採用動態規劃的思想,用乙個陣列dp i j 記錄a字串中i 1位置到b字串中j 1位置的最長公共子串行,若a i 1 b j 1 那麼dp i j dp i 1 j 1 1,若不相同,那麼dp i j 就是dp i 1 j 和dp i j 1 中的較大者。class lcs el...