分析:求最长重复子序列,即说明要找到一个至少出现两次的最长的子序列。假设某个子序列第二次出现和第一次出现的位置相差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); } }