ocaml: phase 5.1 count_palindromes.ml baseline ("aabaa" -> 9 palindromes)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s

Expand-around-center linear-time palindrome counting:

  for c = 0 to 2*n - 2 do
    let l = ref (c / 2) in
    let r = ref ((c + 1) / 2) in
    while !l >= 0 && !r < n && s.[!l] = s.[!r] do
      count := !count + 1; l := !l - 1; r := !r + 1
    done
  done

The 2n-1 centers cover both odd (c even -> l = r) and even
(c odd -> l = r - 1) palindromes.

For "aabaa":
  5 singletons + 2 "aa" + 1 "aba" + 1 "aabaa" = 9

Complements lps_dp.ml (longest subsequence) and manacher.ml
(longest substring); this one *counts* all palindromic substrings.

187 baseline programs total.
This commit is contained in:
2026-05-11 03:14:23 +00:00
parent aaa6020037
commit d3340107e6
3 changed files with 27 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
let count_pal s =
let n = String.length s in
let count = ref 0 in
for c = 0 to 2 * n - 2 do
let l = ref (c / 2) in
let r = ref ((c + 1) / 2) in
while !l >= 0 && !r < n && s.[!l] = s.[!r] do
count := !count + 1;
l := !l - 1;
r := !r + 1
done
done;
!count
;;
count_pal "aabaa"

View File

@@ -32,6 +32,7 @@
"coin_min.ml": 6,
"count_change.ml": 406,
"count_inversions.ml": 12,
"count_palindromes.ml": 9,
"count_subarrays_k.ml": 7,
"csv.ml": 10,
"egg_drop.ml": 8,