Edit Distance

来源:互联网 发布:金融行业数据分析 编辑:程序博客网 时间:2024/06/05 12:27

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character

c) Replace a character

class Solution:    # @return an integer    def minDistance(self, word1, word2):        mark = [[0 for j in range(len(word2)+1)] for i in range(len(word1)+1)]        for i in range(len(word1)+1):            for j in range(len(word2)+1):                if i==0 or j==0:                    if i==0:                        mark[i][j]=j                    else:                        mark[i][j]=i                else:                    if word1[i-1]==word2[j-1]:                        mark[i][j]=mark[i-1][j-1]                    else:                        mark[i][j]=min(mark[i-1][j-1]+1,mark[i][j-1]+1,mark[i-1][j]+1)        return mark[-1][-1]


0 0
原创粉丝点击