longest common str

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

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

    int max = INT_MIN;
    int end_sub_str_a = -1;
    int end_sub_str_b = -1;
    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] = 0;
            }

            if (comm_len_array[i][j] > max) {
                max = comm_len_array[i][j];
                end_sub_str_a = i;
                end_sub_str_b = j;
            }
        }
    }

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

    return max;
}


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

 

posted on 2016-03-15 17:28  walkwalkwalk  阅读(220)  评论(0编辑  收藏  举报

导航