文本编辑距离

来源:互联网 发布:sql 2005 编辑:程序博客网 时间:2024/05/17 03:32

题目:给定一个字符串word。再给定n个字符串s1, s2, ... sn.

求出s中和word相似度最小的字符串。


注意:两个字符串的相似度是,修改s1或s2的中的任一字符,一次只能改一次,或者是在s1或s2的任一位置增加一个字符,一次只能增加一次。是的最后s1 = s2.

比如:helo -> hea。相似度为2。步骤分别是去掉o, 改变l。


分析:设f[i, j] 表示 word(0, i) 和 s(0, j)的文本相似度。

那么 f[i, j] = min(f[i, j-1] + 1, f[i - 1, j], f[i - 1, j - 1] + (word[i] == s[j]? 0: 1));

min中的三个方程的意思分别是:

   s(0, j-1),添加一个s[j],

   word(0, i-1) 添加一个word[i],

   word[i] == s[j]?想的话则由f[i-1, j-1]决定,不相等则修改word[i]或者s[j] 再加上 f[i- 1, j-1]。

#include <cstring>#include <algorithm>#include <iostream>#include <vector>using namespace std;#define MAXN 100int arr[MAXN][MAXN];int dp(const string &s1, const string &s2, int i, int j) {    if (i == -1 && j == -1) {        return 0;    } else if (i == -1) {        return j + 1;    } else if (j == -1) {        return i + 1;    }    if (arr[i][j] >= 0) {        return arr[i][j];    }    int mn = dp(s1, s2, i - 1, j) + 1;    mn = min(mn, dp(s1, s2, i, j - 1) + 1);    mn = min(mn ,dp(s1, s2, i-1, j - 1) + (s1[i] == s2[j]? 0: 1));    arr[i][j] = mn;    return mn;}int main() {    string word;    cin >> word;    int n;    cin >> n;    vector<string> dict(n);    for (int i = 0; i < n; i++) {        cin >> dict[i];    }    vector<int> dist(n);    int mn = (1 << 30);    for (int i = 0; i < n; i++) {        memset(arr, -1, sizeof(arr));        dist[i] = dp(word, dict[i], word.size() - 1, dict[i].size() - 1);        if (dist[i] < mn) {            mn = dist[i];        }    }    for (int i = 0; i < n; i++) {//        cout << dist[i] << " ";        if (dist[i] == mn) {            cout << dict[i] << " ";       }    }    cout << endl;    return 0;}



0 0