第十七周LeetCode算法题
来源:互联网 发布:vb算法大全 编辑:程序博客网 时间:2024/06/05 05:29
题目名称:72. Edit Distance
题目难度:Hard
题目描述:
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
题目分析:
题目要求找出两个字符串之间的“编辑距离”,即用最小的步骤将两个字符串变成一样的。
可以用动态规划思想去做。
设需要计算编辑距离的两个字符串分别为x[1..m]和 y[1..n],维护一个二维数组E[i][j],表示a[1..i]和b[1..j]的编辑距离.
E[i][j]与前面的值有关
要么就是在a[1..i-1]和b[1..j]的编辑距离的基础上,a字符再向前一步,变成a[1..i]和b[1..j],那么此时E[i][j]就是E[i - 1][j] + 1
要么就是在a[1..i]和b[1..j-1]的编辑距离的基础上,b字串再向前一步,变成a[1..i]和b[1..j],那么此时E[i][j]就是E[i][j - 1] + 1
要么就是在a[1..i-1]和b[1..j-1]的编辑距离的基础上,a、b的字符均再向前一步,变成a[1..i]和b[1..j],那么此时E[i][j]就是E[i - 1][j - 1] + diff(x[i - 1], y[j - 1]
其中,当x[i]=y[j]时, diff(i, j)=0;否则diff(i, j)=1.
即:
当i = 0时,E[i][j] = j;当j = 0时,E[i][j] = i;
当i > 0,j > 0时,E[i][j] = min(E[i - 1][j] + 1, E[i][j - 1] + 1, E[i - 1][j - 1] + diff(x[i - 1], y[j - 1]))
其中,当x[i]=y[j]时, diff(i, j)=0;否则diff(i, j)=1.
最后AC的代码是:
class Solution {public: bool diff(char a, char b) { return !(a == b); } int min(int a, int b, int c) { if (a <= b && a <= c) return a; if (b <= a && b <= c) return b; if (c <= a && c <= b) return c; } int minDistance(string word1, string word2) { if (word1 == "") return word2.size(); if (word2 == "") return word1.size(); if (word1 == word2) return 0; int E[word1.size() + 1][word2.size() + 1]; for (int i = 0; i <= word1.size(); ++i) { E[i][0] = i; } for (int i = 0; i <= word2.size(); ++i) { E[0][i] = i; } for (int i = 1; i <= word1.size(); ++i) { for (int j = 1; j <= word2.size(); ++j) { E[i][j] = min(E[i - 1][j] + 1, E[i][j - 1] + 1, E[i - 1][j - 1] + diff(word1[i - 1], word2[j - 1])); } } return E[word1.size()][word2.size()]; }};