赞
踩
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <algorithm>
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) {
int len1 = str1.length();
int len2 = str2.length();
vector<vector<int>> resultVector(len1+1,vector<int>(len2+1));
//初始化第0行
for (int i = 0; i < len2; i++) {
resultVector[0][i] = 0;
}
//初始化第0列
for (int i = 0; i < len1; i++) {
resultVector[i][0] = 0;
}
/*
计算表达式
|-- 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++) {
//str2
for (int j = 1; j < len2; j++) {
//x[i] == y[j]
if (str1.at(i - 1) == str2.at(j - 1)) {
resultVector[i][j] = resultVector[i - 1][j - 1] + 1;
}
//x[i] != y[j]
else {
resultVector[i][j] = max(resultVector[i - 1][j], resultVector[i][j - 1]);
}
}
}
//输出结果矩阵
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++) {
if (i == 0)
cout << "\t";
else
cout << str1.at(i - 1)<<"\t";
for (int j = 0; j < len2+1; j++) {
cout << resultVector[i][j] << "\t";
}
cout << endl;
}
//计算公共子序列
while (len1 != 0 && len2 != 0) {
if (str1.at(len1 - 1) == str2.at(len2 - 1)) {
resultStr.push_back(str1.at(len1 - 1));
len1--;
len2--;
}
else if (resultVector[len1][len2 - 1] > resultVector[len1 - 1][len2]) {
len2--;
}
else {
len1--;
}
}
//字符串翻转
reverse(resultStr.begin(),resultStr.end());
}
int main()
{
string str1 = "abcdef";
string str2 = "fcddsefe";
string resultStr;
LRC(str1, str2, resultStr);
cout << "str1:\t" << str1 << endl;
cout << "str2:\t" << str2 << endl;
cout << "lrc:\t" << resultStr << endl;
system("pause");
return 0;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。