最长公共字符串

对于最长公共字符串问题:
我的方法是采用动态规划求解,所有格子默认为0,当字符相同时就在对应的格子填入其左上角数字加1的结果。然后格子中的最大值即最大公共字符串的长度。
这里写图片描述

#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
//str1为横向,str2这纵向
const string LCS(const string& str1, const string& str2){
    int x = str1.length();
    int y = str2.length();
    int data[100][100] = {0};

    int pos = -1;
    int max = 0;
    for(int i = 0; i < x; i ++)
    {
        for(int j = 0; j < y; j ++)
        {
            if(str2[j] == str1[i])
            {
                //左上角数字加1
                data[i+1][j+1] = data[i][j] + 1;
                if(data[i+1][j+1] > max)
                {
                    max = data[i+1][j+1];
                    pos = j;
                } 
            }   
        }
    }
    ///获取最长公共字符串
    string res = str2.substr(pos - max + 1 ,max);
    return res;
}
int main(){
    string str1("helloworldandc");
    string str2("world");
    string lcs = LCS(str1, str2);
    cout << lcs << endl;
    return 0;
}
posted @ 2016-09-30 20:47  zq216991  阅读(422)  评论(0编辑  收藏  举报