-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathsuffix_array.go
89 lines (78 loc) · 1.8 KB
/
suffix_array.go
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package suffix
import (
"fmt"
"github.com/youngzhu/algs4-go/strings/sort"
)
// Suffix sorting: given a string, sort the suffixes of that string in ascending order.
// Resulting sorted list is called a suffix array.
type SuffixArray struct {
suffixes []string
n int
}
func NewSuffixArray(txt string) SuffixArray {
n := len(txt)
suffixes := make([]string, n)
for i := 0; i < n; i++ {
suffixes[i] = txt[i:]
}
sort.Quicksort(suffixes)
return SuffixArray{suffixes: suffixes, n: n}
}
// Length
// Returns the length of the input string
func (sa SuffixArray) Length() int {
return sa.n
}
// Index
// Returns the index into the original string of the ith smallest suffix.
func (sa SuffixArray) Index(i int) int {
if i < 0 || i >= sa.n {
panic(`Illegal index: ` + fmt.Sprint(i))
}
return sa.n - len(sa.suffixes[i])
}
// LCP returns the length of the longest common prefix of the ith smallest suffix
// and the i-1 th smallest suffix.
func (sa SuffixArray) LCP(i int) int {
if i < 1 || i >= sa.n {
panic("Illegal argument")
}
return lcp(sa.suffixes[i], sa.suffixes[i-1])
}
// longest common prefix of s and t
func lcp(s, t string) int {
n := min(len(s), len(t))
for i := 0; i < n; i++ {
if s[i] != t[i] {
return i
}
}
return n
}
// Select
// Returns the ith smallest suffix as a string
func (sa SuffixArray) Select(i int) string {
if i < 0 || i >= sa.n {
panic("Illegal argument")
}
return sa.suffixes[i]
}
// Rank
// Returns the number of suffixes strictly less than the query string.
// Note: rank(select(i)) == i
func (sa SuffixArray) Rank(query string) int {
lo, hi := 0, sa.n-1
for lo <= hi {
mid := lo + (hi-lo)/2
midSuffix := sa.suffixes[mid]
switch {
case query < midSuffix:
hi = mid - 1
case query > midSuffix:
lo = mid + 1
default:
return mid
}
}
return lo
}