Skip to content

Commit 9fd00e9

Browse files
committed
Add zAlgorithm
1 parent b8e6d9c commit 9fd00e9

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package io.github.acl4s
2+
3+
import scala.reflect.ClassTag
4+
5+
/**
6+
* Reference:
7+
* D. Gusfield,
8+
* Algorithms on Strings, Trees, and Sequences: Computer Science and
9+
* Computational Biology
10+
*/
11+
private[acl4s] def zAlgorithmImpl[T: ClassTag](s: Array[T]): Array[Int] = {
12+
val n = s.length
13+
if (n == 0) {
14+
return Array.empty
15+
}
16+
val z = new Array[Int](n)
17+
z(0) = 0
18+
var j = 0
19+
for (i <- 1 until n) {
20+
var k = if (j + z(j) <= i) { 0 }
21+
else { Math.min(j + z(j) - i, z(i - j)) }
22+
while (i + k < n && s(k) == s(i + k)) {
23+
k += 1
24+
}
25+
z(i) = k
26+
if (j + z(j) < i + z(i)) {
27+
j = i
28+
}
29+
}
30+
z(0) = n
31+
z
32+
}
33+
34+
def zAlgorithm(s: String): Array[Int] = zAlgorithmImpl(s.toCharArray)
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package io.github.acl4s
2+
3+
class StringSuite extends munit.FunSuite {
4+
5+
test("zAlgorithm") {
6+
{
7+
val str = "abracadabra";
8+
val lcp = zAlgorithm(str)
9+
10+
assertEquals(lcp.toSeq, Seq(11, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1))
11+
}
12+
{
13+
val str = "ababababa"
14+
val lcp = zAlgorithm(str)
15+
16+
assertEquals(lcp.toSeq, Seq(9, 0, 7, 0, 5, 0, 3, 0, 1))
17+
}
18+
}
19+
20+
}

0 commit comments

Comments
 (0)