第七周作业——最长递增子序列
2014-04-24 09:17
253 查看
#include "stdafx.h" #include "string.h" #include <iostream> using namespace std; enum decreaseDir {kInit = 0, kLeft, kUp, kLeftUp}; void LCS_Print(int **LCS_direction, char* pStr1, char* pStr2, size_t row, size_t col); int LCS(char* pStr1, char* pStr2) { if(!pStr1 || !pStr2) return 0; size_t length1 = strlen(pStr1); size_t length2 = strlen(pStr2); if(!length1 || !length2) return 0; size_t i, j; int **LCS_length; LCS_length = (int**)(new int[length1]); for(i = 0; i < length1; ++ i) LCS_length[i] = (int*)new int[length2]; for(i = 0; i < length1; ++ i) for(j = 0; j < length2; ++ j) LCS_length[i][j] = 0; int **LCS_direction; LCS_direction = (int**)(new int[length1]); for( i = 0; i < length1; ++ i) LCS_direction[i] = (int*)new int[length2]; for(i = 0; i < length1; ++ i) for(j = 0; j < length2; ++ j) LCS_direction[i][j] = kInit; for(i = 0; i < length1; ++ i) { for(j = 0; j < length2; ++ j) { //之前此处的代码有问题,现在订正如下: if(i == 0 || j == 0) { if(pStr1[i] == pStr2[j]) { LCS_length[i][j] = 1; LCS_direction[i][j] = kLeftUp; } else { if(i > 0) { LCS_length[i][j] = LCS_length[i - 1][j]; LCS_direction[i][j] = kUp; } if(j > 0) { LCS_length[i][j] = LCS_length[i][j - 1]; LCS_direction[i][j] = kLeft; } } } else if(pStr1[i] == pStr2[j]) { LCS_length[i][j] = LCS_length[i - 1][j - 1] + 1; LCS_direction[i][j] = kLeftUp; } else if(LCS_length[i - 1][j] > LCS_length[i][j - 1]) { LCS_length[i][j] = LCS_length[i - 1][j]; LCS_direction[i][j] = kUp; } else { LCS_length[i][j] = LCS_length[i][j - 1]; LCS_direction[i][j] = kLeft; } } } LCS_Print(LCS_direction, pStr1, pStr2, length1 - 1, length2 - 1); //调用下面的LCS_Pring 打印出所求子串。 return LCS_length[length1 - 1][length2 - 1]; //返回长度。 } void LCS_Print(int **LCS_direction, char* pStr1, char* pStr2, size_t row, size_t col) { if(pStr1 == NULL || pStr2 == NULL) return; size_t length1 = strlen(pStr1); size_t length2 = strlen(pStr2); if(length1 == 0 || length2 == 0 || !(row < length1 && col < length2)) return; if(LCS_direction[row][col] == kLeftUp) { if(row > 0 && col > 0) LCS_Print(LCS_direction, pStr1, pStr2, row - 1, col - 1); printf("%c", pStr1[row]); } else if(LCS_direction[row][col] == kLeft) { if(col > 0) LCS_Print(LCS_direction, pStr1, pStr2, row, col - 1); } else if(LCS_direction[row][col] == kUp) { if(row > 0) LCS_Print(LCS_direction, pStr1, pStr2, row - 1, col); } } int _tmain(int argc, _TCHAR* argv[]) { char* pStr1="abcde"; char* pStr2="acde"; LCS(pStr1,pStr2); printf("\n"); system("pause"); return 0; }
程序运行结果如下所示:
相关文章推荐
- 第七周作业—最长递增子序列
- 第七周作业3——最长递增子序列
- 第7周作业3——最长递增子序列
- 第七周作业——动态规划求最大递增子序列
- 第七周作业--最长子序列
- 第7周作业3——最长递增子序列
- 第7周作业3——最长递增子序列
- 寻找最长递增子序列 的两方法效率比较
- 最长递增子序列
- C++计算整数序列的最长递增子序列的长度
- 求解最长递增子序列长度|动态规划+二分查找:C\C++实现
- (软件项目与过程管理)第七周作业
- NYOJ201-作业题(最长升降子序列)
- 【土狗之路】coursera上C语言基础第七周作业
- 最长递增子序列(时间复杂度n*logn)
- 华为OJ训练题——最长递增子序列问题
- 第七周,,作业一,数组求和,求最值
- 第七周作业
- 第七周作业
- c++第四章剩下作业(第七周)