ocaml: phase 5.1 lps_dp.ml baseline (LPS "BBABCBCAB" = 7)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Standard O(n^2) length-major DP for longest palindromic
subsequence:
dp[i][j] = dp[i+1][j-1] + 2 if s[i] = s[j]
= max(dp[i+1][j], dp[i][j-1]) otherwise
lps "BBABCBCAB" = 7 (witness "BABCBAB" etc.)
Complementary to manacher.ml (longest palindromic *substring*,
also length 7 on that input by coincidence) — this is the
subsequence variant which doesn't require contiguity.
Tests length-major fill order, inline if for the length-2 base
case, double-nested for with derived j = i + len - 1.
177 baseline programs total.
This commit is contained in:
@@ -85,6 +85,7 @@
|
||||
"floyd_warshall.ml": 9,
|
||||
"lis.ml": 6,
|
||||
"list_ops.ml": 30,
|
||||
"lps_dp.ml": 7,
|
||||
"lru_cache.ml": 499,
|
||||
"luhn.ml": 2,
|
||||
"magic_square.ml": 65,
|
||||
|
||||
21
lib/ocaml/baseline/lps_dp.ml
Normal file
21
lib/ocaml/baseline/lps_dp.ml
Normal file
@@ -0,0 +1,21 @@
|
||||
let lps s =
|
||||
let n = String.length s in
|
||||
let dp = Array.init n (fun _ -> Array.make n 0) in
|
||||
for i = 0 to n - 1 do dp.(i).(i) <- 1 done;
|
||||
for len = 2 to n do
|
||||
for i = 0 to n - len do
|
||||
let j = i + len - 1 in
|
||||
if s.[i] = s.[j] then
|
||||
dp.(i).(j) <- (if len = 2 then 2 else dp.(i + 1).(j - 1) + 2)
|
||||
else begin
|
||||
let a = dp.(i + 1).(j) in
|
||||
let b = dp.(i).(j - 1) in
|
||||
dp.(i).(j) <- if a > b then a else b
|
||||
end
|
||||
done
|
||||
done;
|
||||
dp.(0).(n - 1)
|
||||
|
||||
;;
|
||||
|
||||
lps "BBABCBCAB"
|
||||
Reference in New Issue
Block a user