leetcode 72. Edit Distance 编辑距离(字符串动态规划)

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = “horse”, word2 = “ros”
Output: 3
Explanation:
horse -> rorse (replace ‘h’ with ‘r’)
rorse -> rose (remove ‘r’)
rose -> ros (remove ‘e’)
Example 2:
Input: word1 = “intention”, word2 = “execution”
Output: 5
Explanation:
intention -> inention (remove ‘t’)
inention -> enention (replace ‘i’ with ‘e’)
enention -> exention (replace ‘n’ with ‘x’)
exention -> exection (replace ‘n’ with ‘c’)
exection -> execution (insert ‘u’)
中文:给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
插入一个字符
删除一个字符
替换一个字符


非常经典的题目。一般字符串求极值的题,第一要想到字符串的动态规划算法
算法:
leetcode 72. Edit Distance 编辑距离(字符串动态规划)_第1张图片
leetcode 72. Edit Distance 编辑距离(字符串动态规划)_第2张图片
代码:

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1=word1.size();
        int len2=word2.size();
        vector> dp(len1 + 1, vector(len2 + 1));
        for (int i=0;i<=len1;i++) dp[i][0]=i;
        for (int j=0;j<=len2;j++) dp[0][j]=j;
        for(int i=1;i<=len1;i++){
            for(int j=1;j<=len2;j++){
                int diff;
                if(word1[i-1]==word2[j-1])
                    diff=0;
                else
                    diff=1;
                int temp=min(dp[i-1][j]+1,dp[i][j-1]+1); //min一次只能求2个
                dp[i][j]=min(temp,dp[i-1][j-1]+diff);
            }
        }
        return dp[len1][len2];
    }
};

语法注意:
1.二维数组的申请:

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

2.min(a,b):即min一次只能求两个的最小值

你可能感兴趣的:(LeetCode,动态规划)