leetcode: 72. Edit Distance
来源:互联网 发布:二手玫瑰知乎 编辑:程序博客网 时间:2024/06/05 19:27
Q
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
AC
class Solution(object): def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ distance = [[i] for i in xrange(len(word1) + 1)] distance[0] = [j for j in xrange(len(word2) + 1)] for i in xrange(1, len(word1) + 1): for j in xrange(1, len(word2) + 1): insert = distance[i][j - 1] + 1 delete = distance[i - 1][j] + 1 replace = distance[i - 1][j - 1] if word1[i - 1] != word2[j - 1]: replace += 1 distance[i].append(min(insert, delete, replace)) return distance[-1][-1]# Time: O(n * m)# Space: O(n + m)class Solution2(object): # @return an integer def minDistance(self, word1, word2): if len(word1) < len(word2): return self.minDistance(word2, word1) distance = [i for i in xrange(len(word2) + 1)] for i in xrange(1, len(word1) + 1): pre_distance_i_j = distance[0] distance[0] = i for j in xrange(1, len(word2) + 1): insert = distance[j - 1] + 1 delete = distance[j] + 1 replace = pre_distance_i_j if word1[i - 1] != word2[j - 1]: replace += 1 pre_distance_i_j = distance[j] distance[j] = min(insert, delete, replace) return distance[-1]# Time: O(n * m)# Space: O(n * m)class Solution3(object): def minDistance(self, word1, word2): distance = [[i] for i in xrange(len(word1) + 1)] distance[0] = [j for j in xrange(len(word2) + 1)] for i in xrange(1, len(word1) + 1): for j in xrange(1, len(word2) + 1): insert = distance[i][j - 1] + 1 delete = distance[i - 1][j] + 1 replace = distance[i - 1][j - 1] if word1[i - 1] != word2[j - 1]: replace += 1 distance[i].append(min(insert, delete, replace)) return distance[-1][-1]if __name__ == "__main__": assert Solution().minDistance("Rabbit", "Racket") == 3 assert Solution().minDistance("Rabbit", "Rabket") == 2 assert Solution().minDistance("Rabbit", "Rabbitt") == 1
阅读全文
0 0
- LeetCode 72. Edit Distance
- [LeetCode]72.Edit Distance
- LeetCode --- 72. Edit Distance
- [Leetcode] 72. Edit Distance
- [leetcode] 72.Edit Distance
- [leetcode] 72.Edit Distance
- Leetcode 72. Edit Distance
- LeetCode 72. Edit Distance
- leetcode 72. Edit Distance
- LeetCode 72. Edit Distance
- Leetcode 72. Edit Distance
- Leetcode:72. Edit Distance
- 【LeetCode】72. Edit Distance
- leetCode 72. Edit Distance
- [leetcode] 72. Edit Distance
- [LeetCode] 72. Edit Distance
- leetcode 72. Edit Distance
- leetcode 72. Edit Distance
- EditPlus格式化XML
- 选择小程序的8大理由,让你拒绝说No
- map使用下标[]还是insert
- C/C++解析XML,pugixml库的使用
- 分布式事务-下单、支付案例
- leetcode: 72. Edit Distance
- LVM
- clk_get_rate函数
- Java三目运算符
- leetcode: 73. Set Matrix Zeroes
- 数据库索引是怎样工作的?
- Redis & Hash
- Golang连接SQLite、MySQL、ORacle
- studio 3.0版本使用ButterKnife