編輯距離的Ruby實現

2021-06-11 01:20:31 字數 2673 閱讀 7954

利用動態規劃演算法,實現最短編輯距離的計算。

#encoding: utf-8

#author: xu jin

#date: nov 12, 2012

#editdistance

#to find the minimum cost by using editdistance algorithm

#example output:

# "please input a string: "

# exponential

# "please input the other string: "

# polynomial

# "the expected cost is 6"

# the result is :

# ["e", "x", "p", "o", "n", "e", "n", "-", "t", "i", "a", "l"]

# ["-", "-", "p", "o", "l", "y", "n", "o", "m", "i", "a", "l"]

p "please input a string: "

x = gets.chop.chars.map

p "please input the other string: "

y = gets.chop.chars.map

x.unshift(" ")

y.unshift(" ")

e = array.new(x.size)

flag = array.new(x.size)

del, ins, cha, fit = (1..4).to_a #deleat, insert, change, and fit

def edit_distance(x, y, e, flag)

(0..x.length - 1).each

(0..y.length - 1).each

diff = array.new(x.size)

for i in(1..x.length - 1) do

for j in(1..y.length - 1) do

diff[i][j] = (x[i] == y[j])? 0: 1

e[i][j] = [e[i-1][j] + 1, e[i][j - 1] + 1, e[i-1][j - 1] + diff[i][j]].min

if e[i][j] == e[i-1][j] + 1

flag[i][j] = del

elsif e[i][j] == e[i-1][j - 1] + 1

flag[i][j] = cha

elsif e[i][j] == e[i][j - 1] + 1

flag[i][j] = ins

else flag[i][j] = fit

end

endend

endout_x, out_y = ,

def solution_structure(x, y, flag, i, j, out_x, out_y)

case flag[i][j]

when fit

out_x.unshift(x[i])

out_y.unshift(y[j])

solution_structure(x, y, flag, i - 1, j - 1, out_x, out_y)

when del

out_x.unshift(x[i])

out_y.unshift('-')

solution_structure(x, y, flag, i - 1, j, out_x, out_y)

when ins

out_x.unshift('-')

out_y.unshift(y[j])

solution_structure(x, y, flag, i, j - 1, out_x, out_y)

when cha

out_x.unshift(x[i])

out_y.unshift(y[j])

solution_structure(x, y, flag, i - 1, j - 1, out_x, out_y)

end#if flag[i][j] == nil ,go here

return if i == 0 && j == 0

if j == 0

out_y.unshift('-')

out_x.unshift(x[i])

solution_structure(x, y, flag, i - 1, j, out_x, out_y)

elsif i == 0

out_x.unshift('-')

out_y.unshift(y[j])

solution_structure(x, y, flag, i, j - 1, out_x, out_y)

endendedit_distance(x, y, e, flag)

p "the expected edit distance is #"

solution_structure(x, y, flag, x.length - 1, y.length - 1, out_x, out_y)

puts "the result is : \n #\n #"

最短編輯距離演算法實現

一,演算法介紹 在cs124課程的第一周提到 求解兩個字串相似度的演算法 minimum edit distance 最短編輯距離 演算法。該演算法在nlp 自然語言處理 中也會用到。如何定義相似度呢?任給兩個字串x 和y,使用以下三種操作將 字串x 變到 字串y 插入 insert 操作 刪除操作...

編輯距離及編輯距離演算法

編輯距離概念描述 編輯距離,又稱levenshtein距離,是指兩個字串之間,由乙個轉成另乙個所需的最少編輯操作次數。許可的編輯操作包括將乙個字元替換成另乙個字元,插入乙個字元,刪除乙個字元。例如將kitten一字轉成sitting sitten k s sittin e i sitting g 俄...

編輯距離及編輯距離演算法

include include include using namespace std const int max 1001 int maxlen max max int maxlen string str1,string str2 return maxlen len1 len2 int main ...