leetcode 72 Edit distance

编辑距离的作用主要是用来比较两个字符串的相似度的

基本的定义如下所示:

编辑距离,又称Levenshtein距离(莱文斯坦距离也叫做Edit Distance),是指两个字串之间,由一个转成另一个所需的最少编辑操作次数,如果它们的距离越大,说明它们越是不同。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。

这个概念是由俄罗斯科学家Vladimir Levenshtein在1965年提出来的,所以也叫 Levenshtein 距离。它可以用来做DNA分析,拼字检测,抄袭识别等等。总是比较相似的,或多或少我们可以考虑编辑距离。

代码1:时间复杂度为O(m*n)

static int x = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    int minDistance(string word1, string word2) {
        //任意一个字母,修改的优先级高于(删除+插入)
        if(word1.size()==0)
            return word2.size();
        if(word2.size()==0)
            return word1.size();
        vector<vector<int>> step(word2.size()+1,vector<int>(word1.size()+1,0));
        for(int i=1;i<=word1.size();++i)
        {
            step[0][i] = i;
        }
        for(int i=1;i<=word2.size();++i)
        {
            step[i][0] = i;
        }
        for(int i=1;i<=word2.size();++i)
        {
            for(int j = 1;j<=word1.size();++j)
            {
                if(word2[i-1]==word1[j-1])
                {
                    step[i][j] = step[i-1][j-1];
                }
                else
                {
                    step[i][j] = getMin(step[i-1][j]+1,step[i][j-1]+1,step[i-1][j-1]+1);
                }
            }
        }
        return step[word2.size()][word1.size()];
    }
private:
    int getMin(int a,int b,int c)
    {
        int temp = a<=b?a:b;
        return temp<=c?temp:c;
    }

};

代码2:时间复杂度为O(n):

static int x = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    int minDistance(string word1, string word2) {
        //任意一个字母,修改的优先级高于(删除+插入)
        if(word1.size()==0)
            return word2.size();
        if(word2.size()==0)
            return word1.size();
        vector<int> step(word2.size()+1,0);
        for(int i=1;i<=word2.size();++i)
        {
            step[i] = i;
        }
        for(int i= 1;i<=word1.size();++i)
        {
            int pre = step[0];
            step[0] =i;
            for(int j=1;j<=word2.size();++j)
            {
                int temp = step[j];
                if(word1[i-1]==word2[j-1])
                {
                    step[j] = pre;
                }
                else
                {
                    step[j]=getMin(step[j],step[j-1],pre)+1;
                }
                pre = temp;
            }
        }
        return step[word2.size()];
    }
private:
    int getMin(int a,int b,int c)
    {
        int temp = a<=b?a:b;
        return temp<=c?temp:c;
    }
};

猜你喜欢

转载自blog.csdn.net/qianli2333/article/details/80668683