forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ZAlgorithm.swift
65 lines (52 loc) · 1.44 KB
/
ZAlgorithm.swift
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
/* Z-Algorithm for pattern/string pre-processing
The code is based on the book:
"Algorithms on String, Trees and Sequences: Computer Science and Computational Biology"
by Dan Gusfield
Cambridge University Press, 1997
*/
import Foundation
func ZetaAlgorithm(ptrn: String) -> [Int]? {
let pattern = Array(ptrn)
let patternLength = pattern.count
guard patternLength > 0 else {
return nil
}
var zeta = [Int](repeating: 0, count: patternLength)
var left = 0
var right = 0
var k_1 = 0
var betaLength = 0
var textIndex = 0
var patternIndex = 0
for k in 1 ..< patternLength {
if k > right {
patternIndex = 0
while k + patternIndex < patternLength &&
pattern[k + patternIndex] == pattern[patternIndex] {
patternIndex = patternIndex + 1
}
zeta[k] = patternIndex
if zeta[k] > 0 {
left = k
right = k + zeta[k] - 1
}
} else {
k_1 = k - left + 1
betaLength = right - k + 1
if zeta[k_1 - 1] < betaLength {
zeta[k] = zeta[k_1 - 1]
} else if zeta[k_1 - 1] >= betaLength {
textIndex = betaLength
patternIndex = right + 1
while patternIndex < patternLength && pattern[textIndex] == pattern[patternIndex] {
textIndex = textIndex + 1
patternIndex = patternIndex + 1
}
zeta[k] = patternIndex - k
left = k
right = patternIndex - 1
}
}
}
return zeta
}