使用动态分析求解,abc->xy,需要几步操作
增加、删除、替换一个字母算一步
# -*- coding: UTF-8 -*-
start = 'abc'
end = 'yz'
s = len(start) + 1
e = len(end) + 1
# 生成二维数组
arr = [[0 for i in range(e)] for j in range(s)]
for i in range(e):
arr[0][i] = i
for i in range(1, s):
arr[i][0] = i
for j in range(1, e):
if start[i-1] == end[j-1]:
arr[i][j] = arr[i-1][j-1]
else:
arr[i][j] = min(arr[i-1][j-1], arr[i][j-1], arr[i-1][j]) + 1
print(arr[s-1][e-1])