求一个字符串的最长重复子序列

分析:求最长重复子序列,即说明要找到一个至少出现两次的最长的子序列。假设某个子序列第二次出现和第一次出现的位置相差i,则i的值为1,2,、、、,str.size()-1,代码如下所示:

string longestRepeatSubstring(const string&str)
{
     int n = str.size();
    if (n==0)
        return NULL;
    int maxLength = 0;
    int startIndex = 0;

for (int i = 1; i < n; ++i) { int current = 0; for (int j = 0; j < n-i; ++j) { if (str[j] == str[i+j])current++; else current = 0; if (current > maxLength) { maxLength = current; startIndex = j-current+1; } } } if (maxLength > 0) { cout << maxI << endl; return str.substr(startIndex,maxLength); } }

 

posted @ 2015-10-14 11:03  Rosanne  阅读(322)  评论(0编辑  收藏  举报