///|
/// OSA(Optimal String Alignment)距离,又称「受限 Damerau-Levenshtein」。
///
/// 与 Levenshtein 的差别是多允许一种编辑操作:相邻两字符的一次对换(代价 1)。
/// 「受限」指每个子串只允许参与一次对换,因此不会像
/// [`damerau_levenshtein_distance`] 那样把多次对换链式组合。
/// 时间复杂度 `O(len(a) * len(b))`。
pub fn osa_distance(a : String, b : String) -> Int32 {
let x = a.to_array()
let y = b.to_array()
let n = x.length()
let m = y.length()
if n == 0 {
return m
}
if m == 0 {
return n
}
let w = m + 1
let d = Array::make((n + 1) * w, 0)
for i = 0; i <= n; i = i + 1 {
d[i * w] = i
}
for j = 0; j <= m; j = j + 1 {
d[j] = j
}
for i = 1; i <= n; i = i + 1 {
for j = 1; j <= m; j = j + 1 {
let cost = if x[i - 1] == y[j - 1] { 0 } else { 1 }
let mut best = min3(
d[(i - 1) * w + (j - 1)] + cost,
d[(i - 1) * w + j] + 1,
d[i * w + (j - 1)] + 1,
)
if i > 1 && j > 1 && x[i - 1] == y[j - 2] && x[i - 2] == y[j - 1] {
let transposed = d[(i - 2) * w + (j - 2)] + 1
if transposed < best {
best = transposed
}
}
d[i * w + j] = best
}
}
d[n * w + m]
}
///|
/// 完整的(非受限)Damerau-Levenshtein 距离,对应 RapidFuzz 的
/// `DamerauLevenshtein.distance`。
///
/// 允许一次编辑操作是「任意间距的两字符对换」,代价为 `1 + 间隔长度` 的一半换算:
/// 具体地,把 `x[i-1]` 与 `y[j-1]` 之间所有字符平移过去,代价是
/// `(i - k - 1) + 1 + (j - l - 1)`,其中 `k`、`l` 是两字符上一次出现的位置。
/// 这条规则来自 Lowrance-Wagner 算法,能处理 OSA 处理不了的多步对换
/// (例如 `CA` -> `ABC` 距离为 2,而 OSA 给出 3)。
///
/// 时间复杂度 `O(len(a) * len(b))`,空间 `O(len(a) * len(b))`。
pub fn damerau_levenshtein_distance(a : String, b : String) -> Int32 {
let x = a.to_array()
let y = b.to_array()
let n = x.length()
let m = y.length()
if n == 0 {
return m
}
if m == 0 {
return n
}
let maxdist = n + m
let w = m + 2
// 矩阵带一圈哨兵行列(下标 0),所有格子先填 maxdist。
// 采用 1 基坐标:D(i, j) = d[i * w + j],表大小 (n + 2) x (m + 2)。
let d = Array::make((n + 2) * w, maxdist)
for i = 0; i <= n; i = i + 1 {
d[(i + 1) * w + 1] = i
}
for j = 0; j <= m; j = j + 1 {
d[w + j + 1] = j
}
// da:某个字符在 a 中最后一次出现的位置;db 是它在 b 中的对应位置。
let da : Map[Char, Int32] = Map([])
for i = 1; i <= n; i = i + 1 {
let mut db = 0
for j = 1; j <= m; j = j + 1 {
let k = match da.get(y[j - 1]) {
Some(position) => position
None => 0
}
let l = db
let cost = if x[i - 1] == y[j - 1] {
db = j
0
} else {
1
}
let best = min3(
d[i * w + j] + cost,
d[(i + 1) * w + j] + 1,
d[i * w + (j + 1)] + 1,
)
let transposed = d[k * w + l] + (i - k - 1) + 1 + (j - l - 1)
d[(i + 1) * w + (j + 1)] = min_int(best, transposed)
}
da.set(x[i - 1], i)
}
d[(n + 1) * w + (m + 1)]
}