longest common Subsequence

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

void print_array(int **arr, int m, int n) {
    int i,j;
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}
int longest_common_string(string& str_a, string& str_b) {
    int len_a = str_a.length();
    int len_b = str_b.length();
    if (0 == len_a || 0 == len_b) {
        return 0;
    }
    int rows = len_a + 1;
    int cols = len_b + 1;
    int ** comm_len_array = new int * [rows];
    int i = 0;
    for (i=0; i < rows; i++) {
        comm_len_array[i] = new int[cols];
    }

    int j = 0;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            comm_len_array[i][j] = 0;
        }
    }

    for (i = 1; i < rows; i++) {
        for (j = 1; j < cols; j++) {
            if (str_a[i - 1] == str_b[j - 1]) {
                comm_len_array[i][j] = comm_len_array[i - 1][j - 1] + 1;
            } else {
                comm_len_array[i][j] = max(comm_len_array[i][j - 1], comm_len_array[i - 1][j]);
            }
        }
        print_array(comm_len_array, rows, cols);
        cout << "++++" << endl;
    }

    int max_len = comm_len_array[len_a][len_b];
    for (i=0; i < rows; i++) {
        delete[] comm_len_array[i];
    }
    delete[] comm_len_array;

    return max_len;
}


int main() {
    string stra = "abcbdab";
    string strb = "bdcaba";
    cout << longest_common_string(stra, strb) << endl;
}

 

posted on 2016-03-15 19:44  walkwalkwalk  阅读(228)  评论(0编辑  收藏  举报

导航