标签:style blog io ar color os sp for on
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
解题思路:
典型的动态规划问题,于是先搞一个状态表d[][],至于下标可以因题而异。
分析状态:如果word1为空,要想到达word2,只有插入len2次,也就是状态表中的d[0][len2],同理若word2为空,则删除len1次,即d[len1][0],对于状态d[i][j]来说,表示的意思是:在word1仅包括原word1前i个字符的前提下,转换到word2(仅包含原word2前j个字符)所用的步数,于是我们可以得出下面的转移公式:
1.如果在状态d[i-1][j-1]的基础上,读入的word1[i] == word2[j],那么d[i][j] == d[i-1][j-1],如果不相等,状态d[i][j]可以由d[i-1][j-1]通过替换第i个字符转化得
2.另一种情况是d[i-1][j] -> d[i][j],这种情况的意义是:由word1的前i-1个字符转换到word2的前j个字符步骤已知,那么要得到状态d[i][j],只需要在当状态d[i][j]时删除word1的第i个元素,就回到了状态d[i-1][j],而d[i-1][j]是已知的。
3.另一种情况是d[i][j-1] ->d[i][j],这种情况的意义是:由word2的前i个字符转换到word2的前j-1个字符步骤已知,那么要得到状态d[i][j],只需要在状态d[i][j-1]时插入一个字符就可以得到状态d[i][j]。
综上:状态d[i][j] 分3种情况:d[i-1][j-1] + cost(替换或者保持原样) 或 d[i-1][j] + 1(加1代表删除最后那个元素) 或 d[i][j-1] + 1(加1代表转移到状态d[i][j-1]后插入一个元素)
class Solution { public: int minDistance(string word1, string word2) { int len1 = word1.size(), len2 = word2.size(); int d[len1 + 1][len2 + 1]; if(len1 == 0)return len2; if(len2 == 0)return len1; for(int i=0;i<=len1;++i)d[i][0]=i; for(int j=0;j<=len2;++j)d[0][j]=j; char st1,st2; for(int i=1;i<=len1;++i) { st1 = word1[i-1]; for(int j=1;j<=len2;++j) { st2 = word2[j-1]; int cost = 0; if(st1 == st2) cost = 0; else cost = 1; d[i][j] = min(min(d[i-1][j]+1, d[i][j-1]+1),d[i-1][j-1]+cost); } } return d[len1][len2]; } };
标签:style blog io ar color os sp for on
原文地址:http://www.cnblogs.com/55open/p/4148353.html