标签:
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
题意:求两个字符串的最小编辑距离,就是最少的操作(改,增,删)使得两个字符串相同。
思路:典型的DP,设dp[i][j]表示第一个字符串的前i个(1-i)和第二个字符串的前j个(1-j)的最小编辑距离。那么如果第i个和第j个相同的话,那么
dp[i][j]=dp[i-1][j-1],否则可以替换一下也就是dp[i][j]=dp[i-1][j-1]+1,其他的操作就是增和删,那么就可以取dp[i-1][j]+1、dp[i][j-1]+1、之前的较小值。
class Solution { public: int minDistance(string word1, string word2) { int len1 = word1.length() + 1; int len2 = word2.length() + 1; vector<vector<int> > f(len1, vector<int>(len2)); for (int i = 0; i < len1; i++) f[i][0] = i; for (int i = 0; i < len2; i++) f[0][i] = i; for (int i = 1; i < len1; i++) for (int j = 1; j < len2; j++) { if (word1[i-1] == word2[j-1]) f[i][j] = f[i-1][j-1]; else f[i][j] = f[i-1][j-1] + 1; f[i][j] = min(f[i][j], min(f[i-1][j]+1, f[i][j-1]+1)); } return f[len1-1][len2-1]; } };
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/44873657