給定兩字串 X、Y,允許三種操作:刪除、插入、替換 (代價均為 1),求轉換所需最小操作數,並輸出對齊序列。
e[i][j]:X[1..i] → Y[1..j] 的最小編輯距離。flag[i][j]:記錄最優決策來源 (DEL/INS/CHA/FIT)。e[i][0]=i (全刪)、e[0][j]=j (全插)。e[i][j] = min(e[i-1][j]+1, e[i][j-1]+1, e[i-1][j-1]+diff),diff = (X[i]==Y[j] ? 0 : 1)。print "Please input a string: "
x = gets.chomp.chars.unshift(" ") # 1-based 索引
print "Please input the other string: "
y = gets.chomp.chars.unshift(" ")
DEL, INS, CHA, FIT = 1, 2, 3, 4
e = Array.new(x.size) { Array.new(y.size) }
flag = Array.new(x.size) { Array.new(y.size) }
# 邊界
(x.size).times { |i| e[i][0] = i }
(y.size).times { |j| e[0][j] = j }
# 填表
(1...x.size).each do |i|
(1...y.size).each do |j|
diff = (x[i] == y[j]) ? 0 : 1
del = e[i-1][j] + 1
ins = e[i][j-1] + 1
cha = e[i-1][j-1] + diff
e[i][j] = [del, ins, cha].min
case e[i][j]
when del then flag[i][j] = DEL
when ins then flag[i][j] = INS
when cha then flag[i][j] = (diff==0 ? FIT : CHA)
end
end
end
# 回溯構造對齊序列
out_x, out_y = [], []
def trace(x, y, flag, i, j, out_x, out_y)
return if i==0 && j==0
case flag[i][j]
when FIT, CHA
out_x.unshift(x[i]); out_y.unshift(y[j])
trace(x, y, flag, i-1, j-1, out_x, out_y)
when DEL
out_x.unshift(x[i]); out_y.unshift('-')
trace(x, y, flag, i-1, j, out_x, out_y)
when INS
out_x.unshift('-'); out_y.unshift(y[j])
trace(x, y, flag, i, j-1, out_x, out_y)
else
# 邊界處理
if i==0
out_x.unshift('-'); out_y.unshift(y[j])
trace(x, y, flag, i, j-1, out_x, out_y)
else
out_x.unshift(x[i]); out_y.unshift('-')
trace(x, y, flag, i-1, j, out_x, out_y)
end
end
end
trace(x, y, flag, x.size-1, y.size-1, out_x, out_y)
puts "Edit distance: #{e[x.size-1][y.size-1]}"
puts out_x.join(' ')
puts out_y.join(' ')
Please input a string: exponential
Please input the other string: polynomial
Edit distance: 6
e x p o n e n - t i a l
- - p o l y n o m i a l
O(min(m,n)),但無法回溯路徑。# Ruby 3.2+ 內建
"exponential".levenshtein_distance("polynomial") # => 6
# 或 gem 'levenshtein-ffi' (C 擴充極快)