最短编辑距离
牛客题库连接
__author__ = 'Jade'
"""
solve minimum Edit Distance , time is O(nm) , space is O(nm)
"""
def findAStrtoBStrMinSteps(a_str , b_str):
a_str_len , b_str_len = len(a_str) , len(b_str)
dp = [[0 for j in range(b_str_len + 1)] for i in range(a_str_len + 1)]
for i in range(a_str_len + 1):
dp[i][0] = i
for i in range(b_str_len + 1):
dp[0][i] = i
operator_list = list()
for i in range(a_str_len):
for j in range(b_str_len):
dp[i + 1][j + 1] = min(dp[i][j + 1] + 1 , dp[i + 1][j] + 1 , dp[i][j] if a_str[i] == b_str[j] else dp[i][j] + 1)
a_str_index , b_str_index = a_str_len , b_str_len
while(a_str_index >= 1 or b_str_index >= 1):
if(dp[a_str_index][b_str_index] == dp[a_str_index][b_str_index - 1] + 1):
operator_list.append({"type":"add","index":b_str_index,"value":b_str[b_str_index - 1]})
b_str_index -= 1
elif(dp[a_str_index][b_str_index] == dp[a_str_index - 1][b_str_index] + 1):
operator_list.append({"type":"del","index":a_str_index})
a_str_index -= 1
else:
if(dp[a_str_index][b_str_index] == dp[a_str_index - 1][b_str_index - 1] + 1):
operator_list.append({"type":"update","index":a_str_index,"value":b_str[b_str_index - 1]})
a_str_index -= 1
b_str_index -= 1
operator_list.reverse()
return operator_list , dp[a_str_len][b_str_len]
def main():
a_str = input()
b_str = input()
operator_list , mininum_steps = findAStrtoBStrMinSteps(a_str , b_str)
print('%s transform %s need mininum %d steps'%(a_str , b_str , mininum_steps))
print('operators as follow:')
for opt in operator_list:
if(opt.get('type') == "del"):
print(opt.get('type'),opt.get('index'))
else:
print(opt.get('type') , opt.get("index") , opt.get('value'))
def test():
while True:
try:
a_str , b_str = input().split()
operator_list , minimum_steps = findAStrtoBStrMinSteps(a_str , b_str)
print(minimum_steps)
except:
break
if __name__ == '__main__':
test()