LeetCode 072 Edit Distance
2016-07-08 23:22
399 查看
有3种操作:插入一个字符、删除一个字符、替换一个字符。问需要最少几步操作使一个字符串变到另一个字符串。
跟最长公共字序列类似,使用动态规划求解即可。时间复杂度为O(len1*len2)。
代码:
跟最长公共字序列类似,使用动态规划求解即可。时间复杂度为O(len1*len2)。
代码:
int minDistance(string word1, string word2) { int len1 = word1.length(); int len2 = word2.length(); vector<vector<int>> f(len1 + 1, vector<int>(len2 + 1)); for(int i = 0 ; i <= len1 ; i++) f[i][0] = i; for(int j = 0 ; j <= len2 ; j++) f[0][j] = j; for(int i = 1 ; i <= len1 ; i++) { for(int j = 1 ; j <= len2 ; j++) { if(word1[i - 1] == word2[j - 1]) { f[i][j] = min(f[i - 1][j - 1], min(f[i-1][j], f[i][j - 1]) + 1); } else { f[i][j] = min(f[i - 1][j - 1] + 1, min(f[i-1][j], f[i][j - 1]) + 1); } } } return f[len1][len2]; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解