求串s中出現的第一個最長重復子串及其位置


// --------------------------------------
// 求串S中出現的第一個最長重復字串及其位置
// ---------------------------------------

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

// KMP算法中,next數組所存的是,在第j個字符前存在一個長度為next[j]-1的重復子串
// 重復子串:SubString(S,i,len) = SubString(S,j,len)


void GetNext(string s, int next[], int length) {
 int i = 0;
 int j = -1;
 next[0] = -1;
 while (i < length) {
  if (j == -1 || s[i] == s[j]) {
   i++;
   j++;
   next[i] = j;
  }
  else
   j = next[j];
 }
}

int MaxNext(int a[], int length) {
 int max = -1;
 for (int i = 0; i < length; i++) {
  max = max < a[i] ? a[i] : max;
 }
 return max;
}


int MaxRepSubString(string s,int &l) {
 l = 0;
 int pos = -1,i;
 int max = -1;
 int length = s.length();
 for (i = 0; i < length - 1; i++) {
  string tmp(s, i, length - i);
  int *next = new int[tmp.length()];
  GetNext(tmp, next, tmp.length());
  max = MaxNext(next, tmp.length());
  if (tmp[tmp.length() - 1] == tmp[max]) {
   max = max + 1;
  }
  if (l < max) {
   l = max;
   pos = i;
  }
 }
 return pos;
}

int main() {
 string s = "abaabaa";
 int l;
 int pos = MaxRepSubString(s,l);
 if (pos == -1)
  cout << "不存在" << endl;
 else
 {
  string res(s, pos, l);
  cout << res << endl;
 }

 system("pause");
 return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM