您的位置:首页 > 其它

Edit Distance(两字符串经过最少操作匹配)

2016-04-07 09:28 204 查看


72. Edit Distance

My Submissions

Question
Editorial Solution

Total Accepted: 55602 Total
Submissions: 195784 Difficulty: 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

Subscribe to see which companies asked this question

Show Tags

Show Similar Problems

显然采用动态规划做:

用dp[n+1][m+1]表示需要执行的最少变换次数,则递推方程为:

dp[i+1][j+1] = dp[i][j],                  当word1[i] == word2[j]

dp[i + 1][j + 1] = min(min(dp[i][j] + 1, dp[i][j + 1] + 1), dp[i + 1][j] + 1);  当word1[i] != word2[j]



class Solution
{
public:
int minDistance(string word1, string word2)
{
int len1 = word1.size(), len2 = word2.size();

vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1));

// 左边沿初始化
for (int i = 0; i <= len1; ++i)
dp[i][0] = i;

// 右边沿初始化
for (int i = 0; i <= len2; ++i)
dp[0][i] = i;

for (int i = 0; i < len1; ++i)
{
for (int j = 0; j < len2; ++j)
{
if (word1[i] == word2[j])
dp[i + 1][j + 1] = dp[i][j];
else
dp[i + 1][j + 1] = min(min(dp[i][j] + 1, dp[i][j + 1] + 1), dp[i + 1][j] + 1);
}
}
return dp[len1][len2];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法