Skip to content

Commit e689ced

Browse files
author
Nadim-Mahmud
committed
suffix array added
1 parent 208c41f commit e689ced

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Source/String/Suffix Array.cpp

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
Description : it gives all suffixes in sorted form on an array
3+
the array contains starting position of suffixes in sorted order
4+
Longest common prefix array contains long match with the previous suffix in sorted form
5+
Complexity : O(n^2Logn)
6+
Ex :
7+
8+
0 banana 5 a
9+
1 anana Sort the Suffixes 3 ana
10+
2 nana ----------------> 1 anana
11+
3 ana alphabetically 0 banana
12+
4 na 4 na
13+
5 a 2 nana
14+
So the suffix array for "banana" is {5, 3, 1, 0, 4, 2}
15+
*/
16+
17+
#define MX 10005
18+
19+
int sfa[10009],pos[10009],tmp[10009],lcp[10009],gap=1,ln;
20+
char ss[10009];
21+
bool scmp(int a,int b)
22+
{
23+
if(pos[a]!=pos[b])return pos[a]<pos[b];
24+
a+=gap;
25+
b+=gap;
26+
return (a<ln&&b<ln)?pos[a]<pos[b]:a>b;
27+
28+
}
29+
void buildsa()
30+
{
31+
int i,j;
32+
ln=strlen(ss);
33+
for(i=0;i<=ln;i++){
34+
sfa[i]=i;
35+
pos[i]=ss[i];
36+
}
37+
for(gap=1;;gap*=2){
38+
sort(sfa,sfa+ln,scmp);
39+
for(i=0;i<ln;i++){
40+
tmp[i+1]=tmp[i]+scmp(sfa[i],sfa[i+1]);
41+
}
42+
for(i=0;i<ln;i++)pos[sfa[i]]=tmp[i];
43+
if(tmp[i]==ln-1)break;
44+
}
45+
}
46+
void buildlcp()
47+
{
48+
int i,j,k;
49+
for(i=0,k=0;i<ln;i++){
50+
if(pos[i]==ln-1)continue;
51+
for(j=sfa[pos[i]+1];ss[i+k]==ss[j+k];)k++;
52+
lcp[pos[i]]=k;
53+
if(k)k--;
54+
}
55+
lcp[ln-1] = 0;
56+
}

0 commit comments

Comments
 (0)