编辑距离及编辑距离算法

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

const int MAX = 1001;
int MaxLen[MAX][MAX];

int maxLen(string str1, string str2)
{
    int len1 = str1.length();//
    int len2 = str2.length();//

    for (int i = 0; i < len1; i++)
        MaxLen[i][0] = 0;
    for (int j = 0; j < len2; j++)
        MaxLen[0][j] = 0;

    for (int i = 1; i <= len1; i++)
    {
        for (int j = 1; j <= len2; j++)
        {
            if (str1[i - 1] == str2[j - 1])
                MaxLen[i][j] = MaxLen[i - 1][j - 1] + 1;
            else
                {
                int temp = max(MaxLen[i - 1][j], MaxLen[i][j - 1]);
                MaxLen[i][j]=max(temp,MaxLen[i-1][j-1]);
                }
        }
    }
   
    return MaxLen[len1][len2];
}
int main()
{
    string str;
    int count = 0;

    while (cin >> str)
    {
        int len = str.size();
        if (len == 1)
        {
            cout << 1 << endl;
            continue;
        }

        string revs = str;
        reverse(revs.begin(), revs.end());
        int max_len = maxLen(str, revs);
        cout << len - max_len << endl;
    }

    return 0;
}
View Code

参考:http://www.cnblogs.com/biyeymyhjob/archive/2012/09/28/2707343.html

         这是很经典的动态规划问题。注意其中二维动态数组内存的分配和释放。

         

int edit(const string str1, const string str2)
{
    int m = str1.size();
    int n = str2.size();

    //定义一个m*n的二维数组
    int **ptr = new int*[m+1];
    for (int i = 0; i < m + 1; i++)
        ptr[i] = new int[n + 1];
    //初始化
    for (int i = 0; i < m + 1; i++)
        ptr[i][0] = i;
    for (int j = 0; j < n + 1; j++)
        ptr[0][j] = j;

    for (int i = 1; i < m + 1; i++)
    {
        for (int j = 1; j < n + 1; j++)
        {
            int d;
            int temp = min(ptr[i - 1][j] + 1, ptr[i][j - 1] + 1);
            if (str1[i - 1] == str2[j - 1])
                d = 0;
            else
                d = 1;

            ptr[i][j] = min(temp, ptr[i - 1][j - 1] + d);
        }
    }

    int dis = ptr[m][n];

    //注意释放内存
    for (int i = 0; i < m + 1; i++)
    {
        delete[] ptr[i];
        ptr[i] = nullptr;
    }
    delete[] ptr;
    ptr = nullptr;

    return dis;

}
int main()
{
    string str1;
    string str2;
    cin >> str1;
    cin >> str2;

    edit(str1, str2);

    return 0;
}
View Code

2017腾讯实习题,求最长公共子串的:http://www.nowcoder.com/test/question/done?tid=4822903&qid=44802

同样用DP求子符串与其反串的最长公共子串的长度,然后用总长减去公共子串的长度即可。

原文地址:https://www.cnblogs.com/573177885qq/p/5832328.html