-
Notifications
You must be signed in to change notification settings - Fork 160
/
Longest substring which appears more than once.cpp
74 lines (48 loc) · 1.3 KB
/
Longest substring which appears more than once.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
Given an input string, find the longest substring which appears more than once in the string
*/
/*
solution: suffix array. Any substring must be a prefix of one of origin string's suffix.
O(n^2) time, O(n) space
*/
#include<iostream>
#include<cassert>
#include<vector>
#include<algorithm>
using namespace std;
bool LessThan(const char* p1, const char* p2) {
return strcmp(p1, p2) < 0;
}
void FindLongestDup(const char* str) {
assert(str);
const char* p = str;
vector<const char*> vec; //suffix array pointers
while (*p != 0) {
vec.push_back(p++);
}
sort(vec.begin(), vec.end(), LessThan);
int curmax = 0;
const char* pmax = str;
for (int i = 0; i < vec.size() - 1; ++i) {
int len = 0;
const char* piter1 = vec[i];
const char* piter2 = vec[i+1];
while (*piter1 != 0 && *piter2 != 0 && *piter1 == *piter2) { //two prefix overlap
piter1++, piter2++;
len++;
}
if (len > curmax) {
pmax = vec[i];
curmax = len;
}
}
for (int i = 0; i < curmax; ++i) {
cout<<*pmax++;
}
cout<<endl;
}
int main() {
char s[] = "abcdfscdfbc";
FindLongestDup(s);
return 0;
}