[C++]學習字符串最長公共子序列(非連續)算法

測試代碼

#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;
}

測試結果

這裏寫圖片描述

發佈了167 篇原創文章 · 獲贊 25 · 訪問量 60萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章