Skip to content

Commit 6674f04

Browse files
committed
编辑距离
1 parent bc80328 commit 6674f04

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

edit_distance.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param word1 & word2: Two string.
5+
# @return: The minimum number of steps.
6+
def minDistance(self, word1, word2):
7+
# write your code here
8+
self.cache = [[-1] * len(word2) for i in xrange(len(word1))]
9+
return self._minDistance(word1, 0, word2, 0)
10+
11+
def _minDistance(self, word_1, start_1, word_2, start_2):
12+
if start_1 >= len(word_1):
13+
return len(word_2) - start_2
14+
elif start_2 >= len(word_2):
15+
return len(word_1) - start_1
16+
if self.cache[start_1][start_2] == -1:
17+
# 假设通过插入一个与另一方相同位置一样的字符
18+
dist_1 = 1 + min(self._minDistance(word_1, start_1 + 1, word_2, start_2), \
19+
self._minDistance(word_1, start_1, word_2, start_2 + 1))
20+
# 相同位置如果不同,做一次字符改变,继续处理后面的字符串。
21+
dist_2 = self._minDistance(word_1, start_1 + 1, word_2, start_2 + 1)
22+
if word_1[start_1] != word_2[start_2]:
23+
dist_2 += 1
24+
self.cache[start_1][start_2] = min(dist_1, dist_2)
25+
return self.cache[start_1][start_2]

0 commit comments

Comments
 (0)