给定一个字符串,求出其最长的重复子串。

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;
 
class LongestCommonString
{
    vector<string> suffixArray;
     size_t len;
 public:
 
    //构造方法
     LongestCommonString(string s)
     {
         //构造后缀数组
         for(size_t i = 0; i < s.length(); ++i)
         {
             suffixArray.push_back(s.substr(i));
         }
         //排序
         sort(suffixArray.begin(), suffixArray.end());
         len = suffixArray.size();
     }
 
     //两两比较,返回最长长度的子串
     string lcpCompare()
     {
         size_t maxLength = 0;
         size_t index = 0;
         for(size_t i = 0; i < len - 1; ++i)
        {
             size_t temp = lcp(suffixArray.at(i), suffixArray.at(i+1));
             if(temp > maxLength)
             {
                 maxLength = temp;
                 index = i;
             }
         }
         return suffixArray.at(index).substr(0, maxLength);
     }
 
     //返回重复的长度
     size_t lcp(const string& a, const string& b)
     {
         size_t i = 0;
         while(a[i] == b[i])
         {
             ++i;
         }
         return i;
     }
 };
 
 int main()
{
     string h = "hello";
     string word = "aacaagmtttacaagmc";
     LongestCommonString slcp(word);
     cout << "最长重复子串为:" << slcp.lcpCompare() << endl;
 }

参考资料:http://www.cnblogs.com/jerry19880126/archive/2012/08/05/2623954.html

    原文作者:爱上健身的菇凉
    原文地址: https://blog.csdn.net/XIAXIA__/article/details/8814593
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞