|
12 | 12 | """
|
13 | 13 |
|
14 | 14 | def min_distance(word1, word2):
|
| 15 | + """ |
| 16 | + Finds minimum distance by getting longest common subsequence |
| 17 | +
|
| 18 | + :type word1: str |
| 19 | + :type word2: str |
| 20 | + :rtype: int |
| 21 | + """ |
15 | 22 | return len(word1) + len(word2) - 2 * lcs(word1, word2, len(word1), len(word2))
|
16 | 23 |
|
17 |
| -def lcs(s1, s2, i, j): |
| 24 | +def lcs(word1, word2, i, j): |
18 | 25 | """
|
19 |
| - The length of longest common subsequence among the two given strings s1 and s2 |
| 26 | + The length of longest common subsequence among the two given strings word1 and word2 |
20 | 27 | """
|
21 | 28 | if i == 0 or j == 0:
|
22 | 29 | return 0
|
23 |
| - elif s1[i - 1] == s2[j - 1]: |
24 |
| - return 1 + lcs(s1, s2, i - 1, j - 1) |
| 30 | + if word1[i - 1] == word2[j - 1]: |
| 31 | + return 1 + lcs(word1, word2, i - 1, j - 1) |
| 32 | + return max(lcs(word1, word2, i - 1, j), lcs(word1, word2, i, j - 1)) |
| 33 | + |
| 34 | +def min_distance_dp(word1, word2): |
| 35 | + """ |
| 36 | + Finds minimum distance in a dynamic programming manner |
| 37 | + TC: O(length1*length2), SC: O(length1*length2) |
| 38 | +
|
| 39 | + :type word1: str |
| 40 | + :type word2: str |
| 41 | + :rtype: int |
| 42 | + """ |
| 43 | + length1, length2 = len(word1)+1, len(word2)+1 |
| 44 | + res = [[0 for _ in range(length2)] for _ in range(length1)] |
| 45 | + |
| 46 | + if length1 == length2: |
| 47 | + for i in range(1, length1): |
| 48 | + res[i][0], res[0][i] = i, i |
25 | 49 | else:
|
26 |
| - return max(lcs(s1, s2, i - 1, j), lcs(s1, s2, i, j - 1)) |
| 50 | + for i in range(length1): |
| 51 | + res[i][0] = i |
| 52 | + for i in range(length2): |
| 53 | + res[0][i] = i |
| 54 | + |
| 55 | + for i in range(1, length1): |
| 56 | + for j in range(1, length2): |
| 57 | + if word1[i-1] == word2[j-1]: |
| 58 | + res[i][j] = res[i-1][j-1] |
| 59 | + else: |
| 60 | + res[i][j] = min(res[i-1][j], res[i][j-1]) + 1 |
27 | 61 |
|
28 |
| -# TODO: Using dynamic programming |
| 62 | + return res[len(word1)][len(word2)] |
0 commit comments